1. 程式人生 > >Python進階-----通過類的內置方法__str__和__repr__自定制輸出(打印)對象時的字符串信息

Python進階-----通過類的內置方法__str__和__repr__自定制輸出(打印)對象時的字符串信息

對象 pre 信息 控制臺 定制 def -- 執行 ini

__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__

Python進階-----通過類的內置方法__str__和__repr__自定制輸出(打印)對象時的字符串信息