[英]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.