[英]Accessing a variable within a nested function of the same class
I am trying to access variable
within function_3
- how should I go about doing this?我正在尝试访问
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)
The name self
from here def function_2(self):
shadows name self
from here def function_1(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
I think you want to achieve this behavior我想你想实现这种行为
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
Shout out if I misunderstood what you want to do, but it looks like you need to create an instance of class A, with A(), and then calling function_1 and function_3 on that instance.如果我误解了您想要做什么,请大声喊叫,但看起来您需要使用 A() 创建 class A 的实例,然后在该实例上调用 function_1 和 function_3。 Pardon all the jargon, but I hope you can learn from example below:
请原谅所有的行话,但我希望你能从下面的例子中学习:
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.