[英]Update kivy recycleview self.data from textinput change
[英]“self.data” usage in python
您好我對Python中的屬性用法有疑問。 我了解到在函數定義中我們可以為對象分配一些新屬性,例如:self! 但是,當試圖使用它時,我得到一個錯誤,“...實例沒有屬性'數據'
class Lazy:
def __call__(self, num):
if num is None:
return self.data
# It changes the current object in-place,
# by reassigning the self attribute.
else:
self.data += num
這是我的小代碼。 我對此非常陌生。 我無法弄清楚出了什么問題。 非常感謝你。
如果num is None
,則只分配self.data
,因此在分配之前嘗試訪問它可能會發生。 要防止這種情況,您可以在構造函數中初始化它:
class Lazy:
def __init__(self):
self.data = 0
def __call__(self, num):
if num is None:
return self.data
else:
self.data += num
以下是導致錯誤的事件序列:
您創建了一個新類的實例。 在這一點上,Python對self.data
一無所知:
lazy = Lazy()
你叫它傳遞None
:
lazy(None)
現在,Python輸入__call__
,因為if條件的計算結果為True
它會嘗試返回self.data
。 等一下......它仍然不知道self.data
是什么......所以它吐出一個錯誤。
為了防止這種情況,您必須在嘗試對其值執行某些操作之前分配屬性(例如,從函數返回它們)。 它不必在構造函數中:就在Python第一次嘗試訪問該屬性之前。 對於任何變量都是如此,即以下是不可能的:
print(a) # How do you expect Python to know the value of a?
a = 5 # too late to assign it now...
您正在嘗試引用self.data
但未初始化/聲明它。
class Lazy:
def __init__(self, data=0):
self.data = data #You are initializing data to 0 or a user specified value
def __call__(self, num):
if num is None:
return self.data
# It changes the current object in-place,
# by reassigning the self attribute.
else:
self.data += num
要修改self.data
,必須首先使用類的特殊__init__
方法初始化self.data
屬性。
從官方文檔:
object .__ init __(self [,...])
在創建實例時調用。 參數是傳遞給類構造函數表達式的參數。
所以你可以將self.data
設置為0,那么你的__call__
方法應該按照寫入的方式工作。
class Lazy:
def __init__(self):
self.data = 0
def __call__(self, num):
if num is None:
return self.data
else:
self.data += num
您可以在__init__()
方法或其他任何地方初始化該屬性(盡管__init__()
是推薦的位置)。
嘗試self.data
並初始化它(如果它不存在)。
class Lazy:
def __call__(self, num):
try:
self.data
except:
self.data = 0
if num is None:
return self.data
# It changes the current object in-place,
# by reassigning the self attribute.
else:
self.data += num
我希望它有所幫助。
我想在你的代碼中指出:
class Lazy:
def __init__(self):
self.data = 0
def __call__(self, num):
if num is None:
return self.data
假如你調用你的實例如: lazy(some_value)
那么你的else分支將執行哪個求值為:
else:
self.data += num # self.data = self.data + num
但是,在這種情況下可能存在self.data可能未定義的情況,也會出現上述錯誤。
我同意上述所有答案,但我也需要關注這個問題。
請享用!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.