[英]Application of class instance method results in making class instance variable None?
[英]Printing a class instance results in None if I change the class member values
我遇到了一個我無法解釋的問題:
class A:
def __init__(self, rid, title):
self.rid = rid
self.title = title
self.b = []
def __add__(self, other):
if type(other) == B:
self.b += [other]
def __str__(self):
return self.rid + ' - ' + self.title
def __repr__(self):
return str(self)
class B:
def __init__(self, rid, title):
self.rid = rid
self.title = title
b = B('123', 'abc')
a = A('345', 'cde')
print(a)
a += b
print(a)
第一次打印將產生預期的輸出:
345 - cde
但是,第二次打印(在添加b之后)導致:
None
這是為什么? 我不改變或擺脫的標題a
也沒有我創建一個名為新的和未初始化實例a
,還是我?
表達式a += b
是以下形式的縮寫: a = a.__add__(b)
當你的__add__()
方法返回None
,這意味着你將分配None
以a
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.