首页 > 其他 > 详细

__str__和__repr__

时间:2021-01-05 22:18:02      阅读:21      评论:0      收藏:0      [点我收藏+]

__str__(self)

打印对象时print(obj)时会触发__str__的执行。

class A:
    def __str__(self):
        return ‘str执行了‘
    
    def __repr__(self):
        return ‘repr执行了‘

a = A()
print(a)
str执行了

__repr__(slef)

在命令行中直接输入对象名称即会触发执行。

>>> class A:
...     def __str__(self):
...             print(‘str执行了‘)
...     def __repr__(self):
...             return ‘repr执行了‘
...
>>> a = A()
>>> a
repr执行了

__str__和__repr__的返回值有且必须为字符串。如果没有重写__str__,会触发__repr__,再没写,打印出内存地址。


__str__和__repr__

原文:https://www.cnblogs.com/ChiRou/p/14238002.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!