Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python __repr__ for numbers?

Tags:

python

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()?

like image 792
Dane Larsen Avatar asked Jul 06 '11 21:07

Dane Larsen


People also ask

What is __ repr __ for in Python?

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.

What is the __ repr __ method used for?

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.

What is __ repr __( self?

__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.

What is the purpose of defining the functions __ str __ and __ repr __ within a class how are the two functions different?

__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.


2 Answers

def __repr__(self): 
  return repr(self.i)
like image 120
Ignacio Vazquez-Abrams Avatar answered Nov 24 '22 10:11

Ignacio Vazquez-Abrams


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
like image 36
ironchefpython Avatar answered Nov 24 '22 10:11

ironchefpython