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

 

 

 

 

 

      

相关文章:

  • 2022-12-23
  • 2021-09-01
  • 2021-11-09
  • 2022-02-15
  • 2021-09-09
  • 2022-12-23
  • 2021-07-04
  • 2022-01-09
猜你喜欢
  • 2022-03-10
  • 2021-07-06
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案