I am trying to implement a very basic Java-like Dimension-Class in Python:
class Dimension(object):
def __init__(self, width, height):
self.__width = width
self.__height = height
@property
def width(self):
return self.__width
@property
def height(self):
return self.__height
d = Dimension(800, 400)
print d.width
print d.height
This works fine: d.width returns an int=800, d.height returns an int=400.
But how do I define, that d should return a tuple=(800,400) instead of
<__main__.Dimension object at 0xXXXXXXXX>?
Is there an in-built class function similar to __repr__ for it?
How do I define the returned value of a custom class?
Or do I have to implement a new type?
Thank you
__init__return a tuplewidth, heightbut I guess that's not what you want, since you can't use all the instance methods then. If you want to implement conversion to a tuple then you should implement the__iter__method:return (self.width, self.height).ddoesn't return anything; that is what it is. (Try the same thing with a function.) Methods & functions return values when called; you don't call a class. If you want a method to call to get this type of value, add it to your class.__init__must returnNone, or you'll getTypeErrorwhen you try to create an instance of the class. For your example, you'd getTypeError: __init__() should return None, not 'tuple'.@propertyshould only be used when you need to evaluate some expression. Don't use it when a simple attribute lookup will suffice. Python isn't Java. Only create getters or setters when you really need them..__widthunless you really need to invoke Python's name-mangling machinery. If you need private attributes (which you probably don't in this case), use a single leading underscore. And if you need to ask if you need Python's name-mangling machinery in a particular case, you probably don't. ;)