我怎樣才能在類的方法定義中引用一個類的共享?如何在類的方法定義中引用一個類的授權?
例如:
>>> class C:
... a = 3
... def f(self):
... # nonlocal a # nonlocal doesn't work
... # a = 4 # create a local variable a in f
... self.a = 4
...
>>> c=C()
>>> C.a
3
>>> c.a
4
我怎麼可以參考C.a
在C.f
的定義是什麼?
目前
self.a = 4
將創建c.a
這是從C.a
不同。如果
self.a = 4
替換a = 4
,a
將在C.f
一個局部變量,而不是C.a
nonlocal a
不作a
在f
指C.a
,我不知道爲什麼?
謝謝。
更新:
在類的定義,我什麼時候有資格的屬性,我當不得?舉例來說,我不明白爲什麼以下是錯誤的:
>>> class C:
... C.b=4
...
>>> C.b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'C' has no attribute 'b'
>>> C.C.b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'C' has no attribute 'C'
簡單。使用'C.a = 4'。 –
根據您的更新:這是相當深奧的。當你說「C.b = 4」時,「C」還不存在。您沒有收到錯誤,因爲您在執行此代碼之前已經定義了不同的「C」類。輸入「del C」然後再試一次,你會得到一個錯誤。您正在更新舊的「C」類的類變量,然後使用新的C類重新定義它。 – RobertB