[英]python 3 local variable defined in enclosing scope referenced before assignment
[英]Python local variable defined in an enclosing scope referenced before assignment in multiple functions
我有以下代碼:
class MyFirstClass:
def myDef(self):
global x, y
x = 'some_str'
y = 0
class MySecondClass:
def myOtherDef(self):
for i in range(10):
y += 1
if y % 2 == 0:
y = 0
x = 'new_str'
但是, local variable 'y' defined in an enclosing scope on line 4 referenced before assignment
出現y += 1
錯誤
如何在新的 class 中重新分配變量y
?
這有兩個問題。 首先是您需要將x
和y
定義為MyFirstClass
的成員,而不是方法中的globals
。 您將無法以這種方式訪問它們。 第二個是您需要MyFirstClass
在MySecondClass
的實例:
class MyFirstClass:
x = 'some_str'
y = 0
class MySecondClass:
myFirstClass = MyFirstClass()
def myOtherDef(self):
for i in range(10):
self.myFirstClass.y += 1
if self.myFirstClass.y % 2 == 0:
self.myFirstClass.y = 0
self.myFirstClass.x = 'new_str'
print(self.myFirstClass.x)
mySecondClass = MySecondClass()
mySecondClass.myOtherDef()
Output:
new_str
new_str
new_str
new_str
new_str
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.