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__

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM