Python进阶-----通过类的内置方法__str__和__repr__自定制输出(打印)对象时的字符串信息

__str__方法其实是在print()对象时调用,所以可以自己定义str字符串显示信息,在该方法return一个字符串,如果不是字符串则报错
print(obj) 等同于-->str(obj) 等同于-->obj.__str__

#未自定__str__信息
class Foo:
    def __init__(self,name,age):
        self.name = name
        self.age = age

f = Foo('Menawey',24)
print(f)   #<__main__.Foo object at 0x000002EFD3D264A8>  因为没有定制__str__,则按照默认输出

#自定__str__信息
class Foo:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __str__(self):
        return '名字是%s,年龄是%d'%(self.name,self.age)

f1 = Foo('Meanwey',24)
print(f1)           #名字是Meanwey,年龄是24
s = str(f1)         #---> f1.__str__
print(s)            #名字是Meanwey,年龄是24

__repr__方法是在控制台直接输出一个对象信息或者print一个对象信息时调用,如果自定了__str__信息,print时默认执行__str__
如果没有自定__str__,则print时执行__repr__

#未自定__str__信息,自定了__repr__
class Foo:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __repr__(self):
        return '来自repr-->名字是%s,年龄是%d'%(self.name,self.age)

f2 = Foo('Meanwey',24)
print(f2)               #来自repr-->名字是Meanwey,年龄是24   因为没有自定__str__,则执行__repr__

#自定了__str__信息,自定了__repr__
class Foo:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __str__(self):
        return '来自str-->名字是%s,年龄是%d'%(self.name,self.age)

    def __repr__(self):
        return '来自repr-->名字是%s,年龄是%d'%(self.name,self.age)

f2 = Foo('Meanwey',24)
print(f2)               #来自str-->名字是Meanwey,年龄是24   因为自定了__str__,则print时不会执行__repr__

 

posted @ 2018-10-14 23:47  Meanwey  阅读(2054)  评论(0编辑  收藏  举报