python repr方法和str方法


 

每個類都有默認的__repr__, __str__方法,用print 實例時調用類的str方法,直接輸出類的實例,調用的是類的repr方法

在命令行界面,不用print命令打印而是直接寫變量名,就是用repr方法

用print打印,用str方法

 

自定義一個類,有__str__()方法和__repr__()方法

直接調用調用repr方法,print調用調用str方法

 重寫類的repr和str方法,就可以看出兩者的區別

>>> class P:

...     def __repr__(self):

...         return "hi repr method"

...     def __str__(self):

...         return "hi str method"

...

>>> p=P()

>>> p

hi repr method

>>> print p

hi str method

>>> 

 

>>> s=1
>>> s
1
>>> print s
1


免責聲明!

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



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