__str__()
__str__() 是类的内置方法,用于返回这个类的描述信息,如下,如果没有定义 __str__() 返回的是一个对象,这对我们不是很友好:
class People(object): pass obj = People() print(obj)
[root@localhost ~]$ python 1.py <__main__.People object at 0x7f0e50d74910>
定义了__str__() 后的效果:
class People(object): pass def __str__(self): return "This is a people class." obj = People() print(obj)
[root@localhost ~]$ python 1.py This is a people class.