开发者

How do I access outer functions variables inside a closure(python 2.6)? [duplicate]

开发者 https://www.devze.com 2023-01-16 06:37 出处:网络
This question already has answers here: nonlocal keyword in Python 2.x (10 answers) Closed 4 months ago.
This question already has answers here: nonlocal keyword in Python 2.x (10 answers) Closed 4 months ago.

From wikipedia

I need to access outer functions variables in a similar manner 开发者_JAVA技巧as using the 'nonlocal' keyword from python 3.x. Is there some way to do that in python 2.6? (Not necessarily using the nonlocal keyword)


I always use helper objects in that case:

def outerFunction():
    class Helper:
        val = None
    helper = Helper()

    def innerFunction():
        helper.val = "some value"

This also comes in handy when you start a new thread that should write a value to the outer function scope. In that case, helper would be passed as an argument to innerFunction (the thread's function).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号