簡體   English   中英

Python:當變量和class同名時:UnboundLocalError: local variable 'foo' 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(函數、全局等)中引用和檢索它

所以從上到下查看文件

  1. 在全球范圍內創建 class foo並且foo指向這個 class
  2. 在全球范圍內創建了 class bar
  3. bar中,全局命名空間仍然存在,因此foo仍然指向預先定義的 class。
  4. 但是,當創建 class 時,行foo = foo()告訴 class foo是 function 中的一個變量,並在命名空間中創建一個新鏈接以將foo用於該變量,並且鏈接(至少在bar類)到foo class 丟失
  5. 然后bar嘗試調用foo ,但是有一個與名稱foo相關的空變量

最佳做法是:

  1. 避免命名空間沖突,只需使用不同的變量名
  2. 對類使用大寫,即
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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM