如何在另一个函数内的函数内设置一个类变量?
var.py
class A:
def __init__(self):
self.a = 1
self.b = 2
self.c = 3
def seta(self):
def afunction():
self.a = 4
afunction()
def geta(self):
return self.a
Run Code Online (Sandbox Code Playgroud)
run.py
cA = A()
print cA.a
cA.seta()
print cA.a
print cA.geta()
Run Code Online (Sandbox Code Playgroud)
python run.py
1
1
1
Run Code Online (Sandbox Code Playgroud)
为什么a不等于4,我怎么能让它等于4?
谢谢
对不起,我原来的代码叫做函数 - 忘了.
编辑:
谢谢大家 - 对不起,我刚才看到了.我不小心被我的一个名字所取代....所以我的范围实际上都没问题.
jim*_*mbo 13
问题是有多个self变量.传递给内部函数的参数会覆盖外部函数的范围.
您可以通过self从内部函数中删除参数并确保以某种方式调用该函数来克服此问题.
class A:
def __init__(self):
self.a = 1
self.b = 2
self.c = 3
def seta(self):
def afunction(): # no self here
self.a = 4
afunction() # have to call the function
def geta(self):
return self.a
Run Code Online (Sandbox Code Playgroud)
正如其他人提到的,afunction永远不会被调用。你可以这样做:
class A:
def __init__(self):
self.a = 1
def seta(self):
def afunction(self):
self.a = 4
afunction(self)
def geta(self):
return self.a
a = A()
print a.a
a.seta()
print a.a
Run Code Online (Sandbox Code Playgroud)
这里我们实际上调用afunction并显式传递它self,但这是一种相当愚蠢的设置属性的方法a——特别是当我们可以显式地执行它而不需要 getter 或 setter 时: a.a = 4
或者你可以使用return以下函数:
def seta(self):
def afunction(): #Don't need to pass `self`. It gets picked up from the closure
self.a = 4
return afunction
Run Code Online (Sandbox Code Playgroud)
然后在代码中:
a = A()
a.seta()() #the first call returns the `afunction`, the second actually calls it.
Run Code Online (Sandbox Code Playgroud)