python的class的__str__和__repr__(轉)


本文參考自:

https://stackoverflow.com/questions/18393701/the-difference-between-str-and-repr?noredirect=1&lq=1

在stackoverflow上,有個兄弟問了這個問題:

首先定義一個類:

class Item():
    def __init__(self,name):
        self._name=name

  def __str__(self):
     return "Item's name is :"+self._name
print((Item("Car"),))

返回的是:

C:\Python35\python.exe C:/fitme/work/nltk/1.py
(<__main__.Item object at 0x000001DC3F9BB390>,)

Process finished with exit code 0

 

更改成這樣的代碼后:

class Item():
    def __init__(self,name):
        self._name=name
    # def __str__(self):
    #     return "Item's name is :"+self._name

    def __repr__(self):
        return "Item's name is :" + self._name


print((Item("Car"),))

返回結果是:

C:\Python35\python.exe C:/fitme/work/nltk/1.py
(Item's name is :Car,)

Process finished with exit code 0

有人解答如下:

1.對於一個object來說,__str__和__repr__都是返回對object的描述,只是,前一個的描述簡短而友好,后一個的描述,更細節復雜一些。

2.對於有些數據類型,__repr__返回的是一個string,比如:str('hello') 返回的是'hello',而repr('hello')返回的是“‘hello’”

3.現在是重點了:

Some data types, like file objects, can't be converted to strings this way. The __repr__ methods of such objects usually return a string in angle brackets that includes the object's data type and memory address. User-defined classes also do this if you don't specifically define the __repr__ method.

When you compute a value in the REPL, Python calls __repr__ to convert it into a string. When you use print, however, Python calls __str__.

When you call print((Item("Car"),)), you're calling the __str__ method of the tuple class, which is the same as its __repr__ method. That method works by calling the __repr__ method of each item in the tuple, joining them together with commas (plus a trailing one for a one-item tuple), and surrounding the whole thing with parentheses. I'm not sure why the __str__ method of tuple doesn't call __str__ on its contents, but it doesn't.

 

print(('hello').__str__())
print(('hello').__repr__())

有一個更簡單的例子如下:

from datetime import datetime as dt
print(dt.today().__str__())
print(dt.today().__repr__())
C:\Python35\python.exe C:/fitme/work/nltk/1.py
2017-06-16 11:09:40.211841
datetime.datetime(2017, 6, 16, 11, 9, 40, 211841)

Process finished with exit code 0

  


免責聲明!

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



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