python魔法方法:__repr__与__str__
在Python中,魔法方法(通常称为特殊方法或双下方法)是面向对象编程中的一个重要概念,它们以两个下划线 __ 开头和结尾,例如 __init__
通常,我们定义一个类,
class Test(object):
def __init__(self, value='hello, world!'):
self.data = value
我们打印一个实例化类对象
>> test = Test()
>> test
<__main__.test object at 0x0000018d0ca6cb90>
>> print(test)
<__main__.test object at 0x0000018d0ca6cb90>
这样看实在是不怎么友好,
我们可以使用__str__,__repr__这两个魔法方法,让显示更友好。
- __repr__和__str__这两个方法都是用于显示的,__str__是面向用户的,而__repr__面向程序员。
- 打印对象时首先尝试__str__,它通常应该返回一个友好的显示。 __repr__用于所有其他的环境中:用于交互模式下提示回应以及repr函数,
- 实际上__str__只是覆盖了__repr__以得到更友好的用户显示。当我们想所有环境下都统一显示的话,可以重构__repr__方法
如果只有__repr__魔法方法,代码如下:
class Test(object):
def __init__(self, value='hello, world!'):
self.data = value
def __repr__(self):
return self.data
则类对象输出如下:
>> t=Test()
>> t
hello, world!
>>print(t)
hello, world!
如果同时有__str__和__repr__,代码如下:
class Test(object):
def __init__(self, value='hello, world!'):
self.data = value
def __repr__(self):
return self.data
def __str__(self):
return 'value is %s'%self.data
注意输出的不同
>> t=Test()
>> t
hello, world!
>> print(t)
value is hello, world!
更友好的写法
class Test(object):
def __init__(self,value='hello word'):
self.data=value
def __str__(self):
return self.data
__str__=__repr__