[英]In python3, what's the difference between defining a class method inside or outside __init__ function?
[英]Difference between adding class attribute inside static function and by assignment outside class
有代碼:
class A:
@staticmethod
def g():
A.__z = 4
print(dir(A))
A.g()
print(dir(A)) # A has attribute _A__z
A.__m = 5
print(dir(A)) # A has attribute _A__z and __m
為什么名稱__m
沒有被修改為_A__m
但__z
是?
正如Python教程所說:
只要它出現在類的定義中,就可以在不考慮標識符的句法位置的情況下完成這種修改。
名稱重整發生在編譯時,代碼是在class
語句中的詞法。 對於class
語句之外的代碼,它不會發生。 對於在class
語句外部定義然后添加到類對象的函數中的代碼,不會發生這種情況。 對於由class
語句內的exec
或eval
調用動態執行的代碼,不會發生這種情況。
正是因為你在類之外聲明了它,並且在類內部發生了名稱錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.