[英]Use a class variable in a class method
運行下面的代碼后,我得到了NameError: name 'result' is not defined
。 我嘗試在 class 方法中使用 class 變量。 為什么它給我一個錯誤?
class Test():
def __init__(self):
self.a=self.test1()
self.result = Test.test2()+Test.test3()
def test1(self):
a=100
return a
result = Test.test3()+100
@classmethod
def test2(cls):
b=200
return b
@staticmethod
def test3():
print("Testing3 is calling ")
c=500+Test.result
return c
錯誤:
result = Test.test3()+100
File "<ipython-input-29-29d4025016c1>", line 18, in test3
c=500+result
NameError: name 'result' is not defined
result
不是 class 變量,它是一個實例變量。 實例變量在實例的__init__
期間設置,並在實例 ( self
) 中定義,正如您在此處所做的那樣:
def __init__(self):
self.a=self.test1()
self.result = Test.test2()+Test.test3()
因此,第一次調用test3
時沒有Test.result
值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.