[英]Accessing a variable within a nested function of the same class
我正在嘗試訪問function_3
中的variable
- 我應該如何 go 這樣做?
class A:
def function_1(self):
def function_2(self):
self.variable = 'Hello'
function_2(self)
function_1(self)
def function_3(self):
print(self.variable)
function_3(self)
名稱self
來自這里def function_2(self):
陰影名稱self
來自這里def function_1(self):
class A:
def function_1(self):
def function_2(self): # Here name `self` shadows name `self` from previous line
self.variable = 'Hello'
function_2(self)
function_1(self) # Here you have no `self` variable
def function_3(self):
print(self.variable)
function_3(self) # Here you have no `self` variable too
我想你想實現這種行為
class A:
def function_1(self):
def function_2(x):
x.variable = 'Hello'
function_2(self)
def function_3(self):
print(self.variable)
a = A()
a.function_1()
a.function_3()
> Hello
如果我誤解了您想要做什么,請大聲喊叫,但看起來您需要使用 A() 創建 class A 的實例,然后在該實例上調用 function_1 和 function_3。 請原諒所有的行話,但我希望你能從下面的例子中學習:
class A:
def function_1(self):
def function_2(self):
self.variable = 'Hello'
function_2(self)
def function_3(self):
print(self.variable)
a = A()
a.function_1()
a.function_3()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.