Class Method; returning given input - python

I have the code:
class Triangle(Coordinate):
def __init__(self,xcoord,ycoord,color):
self.color = color
super().__init__(xcoord,ycoord)
(inheriting from class Coordinate)
And whenever I call it, for example
t1 = Triangle(Coordinate(1,1), Coordinate(2,1), Red)
It only returns the coordinates, how do it make it return the color as well?

The answer has been posted in the comments but I think you misunderstood him, so I am going to elaborate a bit more.
Your class Triangle inherits functions from a parents class of some sort. Even though you didn't write a def __str__(self): in Triangle, it can still be used because it is defined in your parent class, and Triangle inherits functions from the parent class
If you don't want to use any of the parent class' functions, you can redefine it in Triangle. When you call that function on a Triangle Python will prefer to use the def __str__(self): in Triangle before referencing the parent class.
In short, you need to write a new def __str__(self): similar to the one in your parent class, but add another portion in the output that accounts for the color. I hope this helps Charmaine. Good luck!

Related

Can I implement an abstact method by a concrete method with a different name?

i am experimenting with implementation of the monte-carlo-tree-search algorithm for the travelling salesman problem. In this context, I have created a class that without going into details looks somewhat like these:
class Position:
def __init__(self, salesman, cities):
self.salesman= salesman
self.cities= cities
def unvisited_cities(self):
result = {}
for name, city in self.cities.items():
if city.not_visited():
result[name] = city
return result
def travel_to_city(self, city_name):
new_salesman = self.salesman.travel_to(city_name)
return Position(new_salesman, self.cities)
Now, I want to declare this class as a child class for an abstact class:
class AbstractGamePosition(metaclass=abc.ABCMeta):
#abc.abstractmethod
def possible_actions(self):
return
But here, I face a problem. Abstact class demands possible_actions method. In my concrete Position class, method that returns a set of all possible actions from is called unvisited_cities, because for the salesman problem only those cities can be the next targets that have not been visited yet. Is it possible to declare a Position as a child class of an AbstactGamePosition abstact class, and somehow let Python know that abstact method possible_actions is implemented in Position class by a concrete method unvisited_cities?
In naive language it could be something like this:
Position <- AbstactGamePosition:
AbstactGamePosition.possible_actions = Position.unvisited_cities
However, Python does not have such a construction. Can this be somehow solved?
Obviously, this can be solved through an interface class:
class Interface(AbstactGamePosition):
def __init__(self, position, concrete_method):
self.position = position
self._possible_actions = concrete_method
def possible_actions(self):
return self._possible_actions(self.position)
position = Position(salesman, cities)
interface = Interface(position, Position.unvisited_cities)
But this looks so sloppy that I find this disgusting.
Given the information in the comments (that you don't want to have a hard dependency between Position and AbstractGamePosition), I think you're looking for the adapter pattern. Your Interface class is pretty close, though I agree that that level of reflection is unwarranted in this situation.
I would recommend created a small class alongside Position that is specifically for position, and that class can delegate to the original.
# (Type annotations provided for clarity; they are optional)
class PositionAdapter(AbstractGamePosition):
def __init__(self, position: Position):
self.position = position
def possible_actions(self):
return self.position.unvisited_cities()
Then, when you want to use a Position in a situation where an AbstractGamePosition is expected, you simply write
my_abstract_game_position = PositionAdapter(my_original_position)
and you can call possible_actions on my_abstract_game_position.
You will have to write one of these adapter classes for each class you want adapted to this abstract parent without a hard dependency. But it's not a lot of boilerplate (five lines of code, basically), so it's worth it if your goal is to keep all of these classes as loosely coupled as possible.
Just implement the method by its expected and required name. You can call you actual implementation internally:
class Position(AbstractGamePosition):
...
def unvisited_cities(self):
...
def possible_actions(self):
return self.unvisited_cities()
In fact, you can simply assign the unvisited_cities method to the required name, which has the same outcome:
class Position(AbstractGamePosition):
...
def unvisited_cities(self):
...
possible_actions = unvisited_cities
ABCMeta literally only cares about the name being defined with an object that does not have an __isabtractmethod__ attribute set to True: that's it.
You can patch Position with
Position.possible_actions = Position.unvisited_cites
then register Position as a subclass of the abstract base class.
AbstractGamePosition.register(Position)
(If fact, registering a virtual subclass doesn't even require the name to be properly defined; you can do so without defining Position.possible_actions.)
(Assuming you can't change the definition of Position to inherit from the abstract class. If you can, #deceze's answer has you covered.)

When to call super(..) and when not to?

I have a simple question regarding the programming style/convention in python when it comes to superclasses, and calling their methods.
Lets assume I have
class A():
def a(self):
print "a"
and I have another class, class B. Is it better to do :-
class B(A):
pass
vs
class B(A):
def a(self):
super(B,self).a()
I eventually want to do : b = B(); b.a()
Is there any difference in the two, except for readability?
You use super when an overriding method should do something in addition to what its base class's method is doing.
For example, if you have class Point and class Circle(Point) and want to implement def move, circles can just reuse point's method they inherit - since moving a circle is precisely moving the circle's centre point.
But if you have class Monster and class Dragon(Monster)... you might want to scorch the land when a dragon walks past, that other monsters would not do. So you'd say that dragon movement is same as normal movement, with some fire added:
class Dragon(Monster):
def move(self, destination):
super(Monster, self).move(destination)
destination.add_some_fire()
If you aren't changing or extending the functionality of the parent method, then there's no reason to even define it - let alone override it. If you don't define it, then the parent method will be used.

Keeping classes loosely coupled and sharing data

I've been working in python on a project where I have a GUI which I split up a bunch of the work between classes. I don't know a lot of the best practices for passing data around between classes, and I've frequently run into the issue, where I have to implement something, or change something for work, and I've resorted to making a lot of the classes objects of another class in order to give it the data I need.
Any ideas or suggests would be greatly appreciated on how to keep my classes independent for later modification and still pass the relevant data around without affecting interfaces too much?
As an example
class Window():
def __init__(self, parent=None):
self.parent = parent
def doStuff(self):
#do work here
class ParseMyWork(Window):
def __init__(self, parent=None):
self.parent=parent
I often find myself doing stuff like the above giving objects to class Window
or simply inheriting everything from them as in ParseMyWork
There must be better and cleaner ways of passing data around without making my classes utterly dependent on eachother, where one little change creates a cascade effect that forces me to make changes in a bunch of other classes.
Any answers to the question don't necessarily have to be in python, but it will be helpful if they are
If I'm understanding your question correctly, I would say that inheritance is not necessary in your case. Why not give ParseMyWork a function for dealing with a specific Window task?
class Window():
def __init__(self, parent=None):
self.parent = parent
def doStuff(self):
#do work here
class ParseMyWork():
def __init__(self, parent=None):
self.parent=parent`
def doWindowActivity(self, window):
window.doStuff
Then you can use the function like this
work_parser = ParseMyWork()
window = Window()
work_parser.doWindowActivity(window);
That way you can use your work_parse instance with any window instance.
Apologies in advance for my Python, it's been a while so if you see any rookie mistakes, do point them out.
Keep it simple.py:
def doStuff(window):
#do work here
return window
def parseStuff(stuff):
pass
really.py:
from simple import doStuff, parseStuff
def really_simple(window):
okay = doStuff(window)
return parseStuff(okay)
don't complicate the class:
from really import really_simple
really_simple(window)
imo: classes are overly complicated objects, and in a lot of cases more confusing than they need to be, plus they hold references and modify stuff, and can be difficult to decouple once they have been tied to other classes. if there isn't a clear reason why a class needs to be used, then it probably doesn't need to be used.
Classes are super powerful, so it's good you're getting started with em.
Discalimer: Haven't worked in python for a while now, so things might not be exact. The general idea still applies though.
Getting into your question now:
I would say the best way to achieve what you want is to create an instance of the first object where you will extract information from.
Now when creating a class, it's vital that you have attributes within them that you will want to be stored within it that you would like to retrieve once the class is instantiated.
For example, using your Window class example above, let's say that you have an attribute called resolution. It would look something like this:
class Window():
def __init__(self, parent = None):
self.parent = None
self.resolution = '40x80'
Now the resolution information associated with your Window class is forever part of any Window class instance. Now, the next step would be to create a get method for resolution. This should be done as follow:
class Window():
def __init__(self, parent = None):
self.parent = None
self.resolution = '40x80'
def getResoultion():
return self.resolution
Now, the reason we created this get method is because we can now set a variable to the information that is returned with it.
So let's say that you have everything associated with your Window class in its own file (let's say the file name is called Window.py). In a separate file (let's call it main.py), you can do the following:
import Window
windowInstance = Window()
windowResolution = windowInstance.getResolution()
If you print out the variable windowResolution, you should get that 40x80 printed out.
Now, as a side note, I do believe it is possible to get the information associated with an attribute with an instance of a class by simply doing something like
windowResolution = windowInstance.resolution
but that is bad practice in general. The reason, in a nutshell, is because you are now exposing attribute names of your class which you do not want to do because it makes it easy for a person outside of your code to learn the name where that information is held and change it. This can then lead to a myriad of other problems when it comes to making an overall program work. That is why it is best practice to use getters and setters. I already showed what getters are. Simply a get method for attributes. Setters, as you can probably assume, allow for one to set the information of an attribute to something else. Now you might say "Gabe, if we can create setter methods, what's the point of it if they just change it". My answer to that is to not give a setter method to all attributes. For attributes you don't mind for a person to change, give it a setter method, but for attributes you do not want any outside users to touch, simply don't create a setter method for it. Same goes with getter methods too. Users don't need to see all of the information of all attributes that makes your program work. Here's a better explanation: https://en.wikipedia.org/wiki/Mutator_method
Now, back to your example. Now let's say you have your ParseMyWork class in its own file like we did with your Window class, and let's say that ParseMyWork needs the resolution info from Window class. You can do the following :
import Window
import ParseMyWork
windowInstance = Window()
windowResolution = windowInstance.getResolution()
parseInstance = ParseMyWork(windowResolution)
This will only pass the window resolution information associated with your Window class. Hope this helps.

Implement same methods in different classes

I really don't know how to word this problem, so I'll try to explain it with an example.
Let's say I have three GUI classes:
Base Surface class
Detailed Surface Class
Sprite Class
All of them are independent of each other, no inheritance among them.
Now I have a function "drag()" that makes a surface/sprite dragable, and I want to implement this function as a method for all three of them.
Since it's the exact same code for all implementations I find it annoying, cumbersome and bad practice to rewrite the code.
The only thing I came up with so far was to make a saperate class for it and inherit this class. But that also doesn't seem to be the way to go.
I'd be very thankfull for some advice.
EDIT
Another example with a slightly different setup - I have the following classes:
BaseSurface
Dragable
Resizable
EventHandler
Only the first one is independent, the others depend on the first (must be inherited).
The end user should, without any effort, be able to choose between a simple BaseSurface, one with that implements dragable, one with resizable, one with eventHandler, and any combination. By "without any effort" I mean the end user should not have to make e custom Class and inherit the desired classes plus call the appropriate methods (init, update, ...) that some classes share.
So what I could do is make a class for every possible combination, eg.
"BaseSurfaceDrag", "BaseSurfaceDragResize", ...
which will get messy really quickly. Whats a different and better approach to this?
This is exactly the kind of case that you should use a parent class for. In both cases it looks like your parent class (logically) should be something like:
class Drawable(object):
def drag(self, *args, **kwargs):
"""Drag and drop behavior"""
# Your code goes here
Then each of your other classes inherits from that
class BaseSurface(Drawable):
# stuff
class DetailedSurface(Drawable):
# stuff
class Sprite(Drawable):
# stuff
In the second case what you have are interfaces, so you could logically do something like:
class DragInterface(object):
"""Implements a `drag` method"""
def drag(self):
"""Drag and drop behavior"""
# Your code goes here
class ResizeInterface(object):
"""Implements a `resize` method"""
def resize(self):
"""Drag and drop resize"""
# Code
class EventHandlerInterface(object):
"""Handles events"""
def handle(self, evt):
# Code
class MyNewSurface(BaseSurface, DragInterface, ResizeInterface):
"""Draggable, resizeable surface"""
# Implement here

Inheritance vs class instance in python module import

Apologies if this doesn't make sense, i'm not much of an experienced programmer.
Consider the following code:
import mymodule
class MyClass:
def __init__(self):
self.classInstance = myModule.classInstance()
and then ......
from mymodule import classInstance
class MyClass(classInstance):
def __init__(self):
pass
If I just wanted to use the one classInstance in MyClass, is it ok to import the specific class from the module and have MyClass inherit this class ?
Are there any best practices, or things I should be thinking about when deciding between these two methods ?
Many thanks
Allow me to propose a different example.
Imagine to have the class Vector.
Now you want a class Point. Point can be defined with a vector but maybe it has other extra functionalities that Vector doesn't have.
In this case you derive Point from Vector.
Now you need a Line class.
A Line is not a specialisation of any of the above classes so probably you don't want to derive it from any of them.
However Line uses points. In this case you might want to start you Line class this way:
class Line(object):
def __init__(self):
self.point1 = Point()
self.point2 = Point()
Where point will be something like this:
class Point(Vector):
def __init__(self):
Vector.__init__(self)
So the answer is really: Depends what you need to do, but when you have a clear idea of what you are coding, than choosing between sub-classing or not becomes obvious.
I hope it helped.
You make it sound like you're trying to "choose between" those two approaches, but they do completely different things. The second one defines a class that inherits from a class (confusingly) called classInstance. The first one defines a class called MyClass (not inheriting from anything except the base obect type) that has an instance variable called self.classInstance, which happens to be set to an instance of the classInstance class.
Why are you naming your class classInstance?

Categories