python的__str__()和__repr__()方法

__str__()和__repe__()方法定义一个值通过print打印时返回时的显示样式

l=list('hello')
print(l)  #['h', 'e', 'l', 'l', 'o']
class animal:
    pass
cat=animal()
print(cat)  #<__main__.animal object at 0x0000021035247748>

上面例子,cat实例的返回不具有可读性,下面通过__str__()和__repr__()方法自定义显示样式。

class animal:
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def __str__(self):
        return 'From __str__(),%s is %s'%(self.name,self.age)
    def __repr__(self):
        return 'From __repr__(),%s is %s'%(self.name,self.age)
cat=animal('cat',10)
print(cat)   #From __str__(),cat is 10

print打印时,先寻找__str__()方法,如果该方法不存在则再寻找__repr__()方法,即两个同时存在时执行__str__()方法。

原文地址:https://www.cnblogs.com/Forever77/p/10099734.html