For instance, say I have a Vector class like this:
class Vector(object):
def __init__(self, x=0.0, y=0.0):
self.x = x
self.y = y
def __str__(self):
return '(%s, %s)' % (self.x, self.y)
If I pass this object to a function as an argument, the function sees it as
<__main__.Vector object at 0x02297E50>
Now, I can make the function know about the Vector in advance(so to speak), so that it knows to access it’s attributes
def foo(vect1, vect2):
return (vect2.x - vect1.x, vect2.y - vect1.y)
But what if I wanted a general function that accepts just a pair of coordinates?
def foo(p1, p2):
return (p2[0] - p1[0], p2[1] -p1[1])
Is there a way to make an object represent itself in a specific manner? For instance, so that I could pass my Vector objects into the above general function without said function needing to know about the object type? So all that it ‘sees’ is the coordinates that make up the objects attributes?
Hopefully that makes sense!
You’ll have to adjust your object to implement certain python hooks to behave in a ‘generic’ way.
In your second example, you could implement the
__getitem__hook to make it behave like a sequence:Or to give a little demonstration:
You already discovered
__str__for your self.