![](/img/trans.png)
[英]UnboundLocalError: local variable 'name' referenced before assignment
[英]Python: When variable and class have the same name: UnboundLocalError: local variable 'foo' referenced before assignment
為了說明,我寫了以下 Python 代碼:
class foo:
def foo_function(self):
return 1
class bar:
def bar_function(self):
foo = foo()
return foo.foo_function()
bar = bar()
print(bar.bar_function())
在 class bar
我需要使用 class foo
的地方。 運行它時出現以下錯誤:
# UnboundLocalError: local variable 'foo' referenced before assignment
此錯誤來自foo = foo()
行,其中變量和 class 具有相同的名稱,如果使用不同的名稱,它將 go 消失,但我想知道內部發生了什么,請注意bar = bar()
沒問題.
順便說一下,這是從另一個 class 使用一個 class 的正確方法嗎?我使用單獨的 class 因為它們是獨立的:例如, foo
是獲取存儲在 AWS 上的秘密,而bar
在不相關的不同應用程序中使用秘密到AWS。
這里的問題是過度使用 python 命名空間。
保存到 memory 中的每個變量都分配了一個name
以在每個 scope(函數、全局等)中引用和檢索它
所以從上到下查看文件
foo
並且foo
指向這個 classbar
bar
中,全局命名空間仍然存在,因此foo
仍然指向預先定義的 class。foo = foo()
告訴 class foo
是 function 中的一個變量,並在命名空間中創建一個新鏈接以將foo
用於該變量,並且鏈接(至少在bar
類)到foo
class 丟失bar
嘗試調用foo
,但是有一個與名稱foo
相關的空變量最佳做法是:
class Foo():
def foo_func():
return 1
foo = Foo()
請注意,即使
bar = bar()
ok 運行,不能再訪問class bar
版本的bar
因為名稱bar
已經被覆蓋,所以bar2 = bar()
會失敗
試試這個看看命名空間發生了什么
class foo:
def foo_function(self):
return 1
print('after class foo')
print(str(foo))
class bar:
def bar_function(self):
print('in bar')
print(str(foo))
foo = foo()
return foo.foo_function()
print('after class bar')
print(str(foo))
print(str(bar))
bar = bar()
print('after instantiating bar')
print(str(bar))
bar.bar_function()
hilton92 的回答是正確的。 您可能還想查看有關 UnboundLocalError 的 python 常見問題解答
但最重要的是,你所做的是一個壞主意,因為它會使你的代碼混亂並且不遵循任何最佳實踐指南。
我建議你閱讀PEP 8——Python 代碼的樣式指南
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.