1, _repr_ && _str_
str面向用户,repr面向程序员
- 当__repr__ str__方法同时定义时
str() 调用_str_ repr() 调用_repr_
print()会调用_str_ 交互环境直接输出会调用_repr_
class Test(object):
def __init__(self, world):
self.world = world
def __str__(self):
return 'world is %s str' % self.world
def __repr__(self):
return 'world is %s repr' % self.world
>>> t = Test('world_hello')
>>> t
world is world_hello repr
>>> print(t)
world is world_hello str
>>> str(t)
'world is world_hello str'
>>> repr(t)
'world is world_hello repr'
>>>
上面代码去掉_str_ 定义时,再看输出
>>> t = Test('world_hello')
>>> print(t)
world is world_hello repr
>>> t
world is world_hello repr
>>> str(t)
'world is world_hello repr'
>>> repr(t)
'world is world_hello repr'
>>>
- 只有_repr_方法定义时
str() repr() 都调用了_repr_方法
print()与实例直接输出 也调用了_repr_方法