繁体   English   中英

Python范围内的嵌套函数?

[英]Python scope inside a nested function inside a class?

如何在另一个函数内的函数内设置一个类变量?

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.py

cA = A()
print cA.a
cA.seta()
print cA.a
print cA.geta()

python run.py

1
1
1

为什么a不等于4,我怎么能让它等于4?

编辑:

谢谢大家 - 对不起,我刚才看到了。 我不小心被我的一个名字所取代....所以我的范围实际上都没问题。

问题是有多个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

正如其他人所说, 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

在这里,我们实际调用afunction ,并明确地传递其self ,但这是设置属性相当愚蠢的方式a -尤其是当我们可以明确地做到这一点,而不需要的getter或setter方法: aa = 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

然后在代码中:

a = A()
a.seta()()  #the first call returns the `afunction`, the second actually calls it.

seta ,您可以定义一个函数

    def afunction(self):
        self.a = 4

...如果它会被调用, 那么self.a设置为4。 但它并没有被称为任何地方,所以a不变。

正如其他几个人所说,你需要在某个时刻实际调用 functiona。 评论不会让我打字这个可理解的,所以这里是一个答案:

def seta(self):
    def functiona(self):  #defined
        self.a = 4
    functiona()           #called

你怎么能把它等于4:

class A:
    def __init__(self):
        self.a = 1
        self.b = 2
        self.c = 3
    def seta(self):
        ##def afunction(self): (remove this)
        self.a = 4 
    def geta(self):
        return self.a

棘手的部分:为什么不等于4 ......

目前a仅通过“功能”设置为4。 由于函数永远不会被调用,所以它永远不会执行.. seta有“函数”嵌套在里面但没有调用...类似于类中的成员变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM