开发者

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_WID开发者_高级运维TH

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


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


But __repr__ can only return a string.

So just do

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


The repr method allows you to define your own string representation of a class instance. It must take only self as a parameter and return a string. Ideally, the repr method should return the information required to build a copy of the instance.To use the repr method do something like:

def __repr__(self):

return f"{self.instance}"

This allows you to return a string representation of your attribute because repr is an inbuilt method in python classes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜