__repr__ 与__str__

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

说明:

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

猜你喜欢

转载自www.cnblogs.com/lighthouse/p/9640709.html