给类或者类的对象添加打印内容 def __repr__(self)

 

通常情况下 打印一个类或者类的对象 会显示 xx.xx object at 0xaaaaabbbbbbb  只会告诉你这个对象或者类 储存在某个内存中,这是因为你的类没有实现相关的打印功能

print (classA)

# [<sort.detection.Detection object at 0x7fdcfd0734a8>, <sort.detection.Detection object at 0x7fdcfdf661d0>]
或者
# <__main__.Foobar instance at 0x7ff2a18c>

类可以通过定义 __repr__() 方法控制这里函数为它的实例返回的内容。

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)

 

测试

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

__str__ 方法没有定义,print t ( 或者 print str(t) ) 将使用 __repr__的结果

如果未定义 __repr__ 方法,则默认使用默认值,这与这里相当。

posted @ 2019-07-24 13:41  clemente  阅读(291)  评论(0编辑  收藏  举报