I have the following (example) code:
class _1DCoord():
def __init__(self, i):
self.i = i
def pixels(self):
return self.i
def tiles(self):
return self.i/TILE_WIDTH
What I want to do is this:
>>> xcoord = _1DCoord(42)
>>> print xcoord
42
But instead I see this:
>>> xcoord = _1DCoord(42)
>>> print xcoord
<_1DCoord instance at 0x1e78b00>
I tried using __repr__ as follows:
def __repr__(self):
return self.i
But __repr__ can only return a string. Is there any way to do what I'm trying to do, or should I just give up and use pixels()?
Python __repr__() function returns the object representation in string format. This method is called when repr() function is invoked on the object. If possible, the string returned should be a valid Python expression that can be used to reconstruct the object again.
The __repr__ method returns the string representation of an object. Typically, the __repr__() returns a string that can be executed and yield the same value as the object. In other words, if you pass the returned string of the object_name.
__repr__ (self) Returns a string as a representation of the object. Ideally, the representation should be information-rich and could be used to recreate an object with the same value.
__str__ is used in to show a string representation of your object to be read easily by others. __repr__ is used to show a string representation of the object.
def __repr__(self):
return repr(self.i)
I believe this is what you're looking for:
class _1DCoord():
def __init__(self, i):
self.i = i
def __repr__(self):
return '_1DCoord(%i)' % self.i
def __str__(self):
return str(self.i)
>>> xcoord = _1DCoord(42)
>>> xcoord
_1DCoord(42)
>>> print xcoord
42
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With