Guy*_*man 0 python interpreter interactive
当我定义一个类并创建它的实例时,在shell中输入实例名称会返回一个内存位置.这并不奇怪,但有没有人知道如何定义一个类,以便将其名称输入shell实际上将返回除内存位置之外的其他内容?
例:
>> import numpy as np
>> foo = np.array([1,2,3])
>> foo
>> array([1, 2, 3])
Run Code Online (Sandbox Code Playgroud)
如果我能得到这样的东西会很好.
这是__repr__方法的用途:
>>> class point(object):
... def __init__(self, x, y):
... self.x = x
... self.y = y
...
... def __repr__(self):
... return "point(%d, %d)" % (self.x, self.y)
>>> x = point(3, 4)
>>> x
point(3, 4)
Run Code Online (Sandbox Code Playgroud)
如果没有自定义__repr__实现,您将在问题中准确地看到您所描述的内容:
>>> class defaultPoint(object):
... def __init__(self, x, y):
... self.x = x
... self.y = y
...
>>> p = defaultPoint(0, 3)
>>> p
<__main__.defaultPoint object at 0x16767b0>
Run Code Online (Sandbox Code Playgroud)