Python __repr__ for numbers?

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 

I want to do the following:

 >>> 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 a way to do what I'm trying to do, or just refuse to use pixels ()?

+6
source share
3 answers
 def __repr__(self): return repr(self.i) 
+9
source

I believe this is what you are 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 
+6
source

But __repr__ can only return a string.

So just

 def __repr__(self): return str(self.i) # or repr(self.i) 

Or, to mimic the usual Python format:

 def __repr__(self): return '_1DCoord(%i)' % self.i 
+5
source

Source: https://habr.com/ru/post/892173/


All Articles