简体   繁体   English

Python:访问嵌套函数中的所有父变量

[英]Python: Access all Parent Variables in Nested Function

On the few occasions I have had to do this I have used the global keyword. 在少数情况下,我不得不使用global关键字。 Currently I am cleaning up some code that's not mine which is basically 200 hundred lines after a While statement with no closures. 目前,我正在清理一些不是我的代码,这基本上是在While语句之后没有闭包的200行代码。 I'd like to separate everything functionally into smaller bits but the problem is that there are a lot of references to the same variables all over those 200 lines. 我想在功能上将所有内容都分成较小的部分,但是问题是在这200行中有很多对相同变量的引用。 Is there a way to give a nested function access to All Parent Variables without declaring them explicitly? 有没有一种方法可以使嵌套函数访问所有父变量而无需显式声明它们?

The original really long while statement: 原来真的很久了:

While True:  
    var1, var2, var3, var4 = x, [], {}, y
    #does something with var2, var3 and var4
    #does something with var1 and var3
    #does something with var4 and var1
    #etc. 

to ---> Edit: Would this be an incorrect solution, if so why? 到--->编辑:这将是一个不正确的解决方案,如果是为什么呢?

class My:
    pass
def foo(): 
   #does something with My.var2, My.var3 and My.var4
def bar(): 
   #does something with My.var1 and My.var3
def tar(): 
    does something with My.var4 and My.var1
While True:
    My.var1, My.var2, My.var3, My.var4 = x, [], {}, y
    #There are a lot of variables to keep track off and declaring each one
    # as global will take a lot of extra declarations
    foo() 
    bar()
    tar() 

Another way to keep track of similar variables is to put them in a class. 跟踪相似变量的另一种方法是将它们放在类中。 For example: 例如:

class MyClass(object):
    def __init__(self, v1, v2, v3, v4):
        self.var1 = v1
        self.var2 = v2
        self.var3 = v3
        self.var4 = v4

    def run(self):
        while True:
            self.foo()
            self.bar()
            self.tar()

    def foo(self):
        """does something with var2, var3 and var4"""
        return self.var2, self.var3, self.var4

    def bar(self):
        """does something with var1 and var3"""
        return self.var1, self.var3

    def tar(self):
        """does something with var4 and var1"""
        return self.var4, self.var1


if __name__ == "__main__":
    mc = MyClass('x', [], {}, 'y')
    mc.run()

Change your functions to use parameters and also get the functions out of that while loop. 更改函数以使用参数,并从while循环中获取函数。

For example: 例如:

def foo(var2, var3, var4)
    return var2 + var3 + var4

def bar(var1, var3)
    return var1 * var3

...
While True:
    var5 = foo(var2,var3,var4)

    var1 = bar(var1,var3) 

etc. 等等

I have a function which calls scipy.optimize.fmin_l_bfgs_b() That function takes another function which is called repeatedly. 我有一个调用scipy.optimize.fmin_l_bfgs_b()的函数,该函数采用了另一个被重复调用的函数。 I have several versions of this same function, using different optimization ways that the user can choose. 我有相同功能的多个版本,使用用户可以选择的不同优化方式。

To keep them all together, I do what you are talking about, but I make sure to do the loop outside of the actual instantiation method. 为了使它们在一起,我正在做您正在谈论的事情,但是我确保在实际的实例化方法之外进行循环。 So, it would look like this: 因此,它看起来像这样:

`def MethodOne(var1, var2): def InnerFn1(...): ... def InnerFn2(...): .... `def MethodOne(var1,var2):def InnerFn1(...):... def InnerFn2(...):....

for i in range(0, var1):
    CallFunctionWhichCallsAnFnAbove(var2, InnerFn1, InnerFn2, i)

` `

That allows me to encapsulate all of the related components together, without any real penalty. 这使我可以将所有相关组件封装在一起,而不会带来任何实际损失。 var1 and var2 are accessible for reading within both inner functions even if you don't add them as parameter in your call, due to standard python scoping. 由于标准的python作用域,即使没有在调用中将它们添加为参数,也可以在两个内部函数中读取var1和var2以便进行读取。

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

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