>>> class Student(object):
... def __init__(self, name):
... self.name = name
... def __str__(self):
... return 'Student object (name: %s)' % self.name
...
>>> s = Student('Michael')
>>> s
<__main__.Student object at 0x00000000022073C8>
>>> print(Student('Michael'))
Student object (name: Michael)
>>>
-------------------------------------------------------------------------------------------
没有写__str __()会调用 __repr__() 方法:
>>> class Student(object):
... def __init__(self, name):
... self.name = name
... def __repr__(self):
... return 'Student object (name: %s)' % self.name
...
>>> print(Student('Michael'))
Student object (name: Michael)
>>> s= Student('Michael')
>>> s
Student object (name: Michael)
>>>
在cmd下运行的Python3.6.5
说明:
用print()打印实例调用的是__str__()方法
不用print()打印实例调用的是__repr__()方法
If a class defines __repr__() but not __str__(), then __repr__() is also used when an “informal” string representation of instances of that class is required.
如果类定义__repr __()但不定义__str __(),那么当需要该类的实例的“informal”字符串表示时,也会使用__repr __()。
参考:
https://docs.python.org/3/reference/datamodel.html?highlight=__repr__#object.__repr__
https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014319098638265527beb24f7840aa97de564ccc7f20f6000
https://www.cnblogs.com/aomi/p/7026532.html