流畅的python第九章笔记 python风格的python

9.1对象表示形式

__repr__和__str__这两个方法都是用于显示的,__str__是面向用户的,而__repr__面向程序员。

我们打印下面的A是默认输出这个对象的类型,我们对B进行了修改__repr__并给返回值,然后我们打印B发现 B对象输出了字符串。

class A():
    def __init__(self,value="this is test"):
         self.name=value
class B(A):
    def __repr__(self):
        return  "B%s"%self.name
class C(A):
    def __str__(self):
        return  "C%s"%self.name
print(A())#
print(B())#
print(C())#

  运行结果如下:

<__main__.A object at 0x01E68790>
Bthis is test
Cthis is test

  

原文地址:https://www.cnblogs.com/c-x-a/p/8942434.html