For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.
进行以下等级测试:
class Test:
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return "<Test a:%s b:%s>" % (self.a, self.b)
def __str__(self):
return "From str method of Test: a is %s, b is %s" % (self.a, self.b)
…它将在Python shell中按以下方式运行:
>>> t = Test(123, 456)
>>> t
<Test a:123 b:456>
>>> print repr(t)
<Test a:123 b:456>
>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
>>> class Test:
... def __repr__(self):
... return "Test()"
... def __str__(self):
... return "member of Test"
...
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test
As Chris Lutz mentioned,这是由类中的
__repr__
方法定义的。从^{} 的文档中:
进行以下等级测试:
…它将在Python shell中按以下方式运行:
如果没有定义
__str__
方法,print(t)
(或print(str(t))
)将使用__repr__
的结果如果没有定义
__repr__
方法,则使用默认值,这相当于。。一种可以应用于任何没有特定格式的类的通用方法可以执行以下操作:
然后
产生
__str__
方法是在打印时发生的,而__repr__
方法是在使用^{如果没有给出
__str__
方法,Python将打印__repr__
的结果。如果您定义了__str__
,而不是__repr__
,Python将使用上面看到的__repr__
,但仍然使用__str__
进行打印。相关问题 更多 >
编程相关推荐