估计是我问题没有描述清楚,这样吧,直接上代码:
class Mylist:
def __init__(self):
self._mylist=list()
def __len__(self):
return len(self._mylist)
def add(self,value):
return self._mylist.append(value)
我自己模仿list的行为。写了一个基本的list,名字叫Mylist,并给他一个add方法用来添加其中的元素,添加完之后,我想输出其中的内容,然后我使用:
list1=Mylist()
list1.add(1)
list1.add(2)
print(list1)
我以为print会显示出list1中的每一项,但是发现实际没有,显示的为:
<__main__.Mylist object at 0x0071A470>
怎么样能让print(list1)显示出的结果和真实list类型一样呢?例如:
[1,2]
__str__具体怎么实现,貌似这个只能为str类型,int不行,而且我发现在pycharm 里面写的时候,提示__str__方法“overrides method in object”
You are using the "aggregation" method to create your own cluster data. At this time, delegation is a simple method:
__str__
is a special method in the Python class. Its return value is the value obtained by usingstr(x)
, andprint(x )
is actually equivalent toprint(str(x))
. In fact, to be more detailed, when we callstr(x)
, we are actually callingx.__str__()
.__str__
是 Python 類中的特殊方法,他的回傳值就是使用str(x)
所得到的值, 而print(x)
其實就等於是print(str(x))
.其實再講細一點,當我們呼叫str(x)
的時候其實是呼叫x.__str__()
.也就是說我們可以這樣想像:
一般我們 自定義的類,
__str__
方法的回傳值是默認的字串,比如說:<__main__.Mylist object at 0x0071A470>
用以說明 namespace, class name 和位置.如果要改變__str__
的回傳值,我們必須要覆寫他.這邊我們讓
__str__
的回傳值為MyList
類中聚合的 list 的__str__
值,這樣就透過委託的方式讓__str__
的輸出跟 list 一樣了.多嘴補充一下,這種在 class 裡面 以雙底線開頭且以雙底線結尾 的 method (俗名叫做魔術方法或是特殊方法),有個正式名稱叫做 "dunder method",對於
__str__
,我們可以唸作 "dunder string".下方評論問的問題我回答在這裡.
首先是不要被混淆,我們利用
print
印出來的內容都是 字串,即便你看到[1, 2]
其實這也是一個字串'[1, 2]'
,只不過內建的幾種資料型態(或我們有覆寫過__str__
的 class) 會想辦法輸出一個帶有該資料型態特徵的字串(通常會非常接近我們產生這些資料時所用的"字面").舉例,我們使用字面產生一個 list:
當我們打印
lst
時,Python 是會製造一個長得像該資料型態字面(甚至一模一樣)的字串讓你印出.所以在這裡
str(list)
並沒有改變 list 中元素的 type,只不過將帶有其特徵的 "字串" 當成回傳值.其次,如果想要在 Python shell (Python的互動介面)中能夠只利用變數名稱就展示用來表示
That is to say, we can imagine it like this:Mylist
的字串,光是__str__
還不夠,這必須要覆寫__repr__
__str__
method is the default string, for example:<__main__.Mylist object at 0x0071A470>
is used to describe namespace, class name and location. If we want to change the return value of__str__
, we must overwrite it. #🎜🎜# #🎜🎜#Here we let the return value of__str__
be the__str__
value of the aggregated list in theMyList
class, so that through delegation The method makes the output of__str__
the same as that of list. #🎜🎜##🎜🎜#I would like to add that this kind of method (commonly known as magic method or special method) in the class that #🎜🎜# starts with a double underline and ends with a double underline #🎜🎜# has an official name called #🎜 🎜#"dunder method"#🎜🎜#, for
__str__
, we can pronounce it as "dunder string". #🎜🎜##🎜🎜#I will answer the questions asked in the comments below. #🎜🎜# #🎜🎜#First of all, don’t be confused. The content we print using
print
is all #🎜🎜# string #🎜🎜#, even if you see[1, 2] In fact, this is also a string
'[1, 2]'
, but it has several built-in data types (or we have overridden__str__
class) will find a way to output a string with the characteristics of the data type (usually very close to the "literal" we used to generate this data). #🎜🎜# #🎜🎜#For example, we use literals to generate a list: #🎜🎜# #🎜🎜#When we printlst
, Python will create a string that looks like the data type literal (or even exactly the same) for you to print. #🎜🎜# #🎜🎜#So herestr(list)
does not change the type of the elements in the list, but only treats the "string" with its characteristics as the return value. #🎜🎜# #🎜🎜#Secondly, if you want to display the string used to representMylist
in the Python shell (Python's interactive interface) using only the variable name, just__str__
Not enough, this must be overridden__repr__
:#🎜🎜# rrreee #🎜🎜##🎜🎜#result#🎜🎜#:#🎜🎜# rrreeeImplement the __str__ function in the class and write the content you want to output
For example
The print function will call the __str__ method of the object. If you have not reimplemented the __str__ method yourself, the __str__ method inherited from the parent class will be used by default, so the output is not necessarily in the form of a list.