0
def method(self, *args):
   def function(*args):
      #can this access all method's variables, data, etc.
4

1 回答 1

1

是的,你可以,因为 python 在查找变量时遵循以下查找规则:

L:local
E:enclosing
G:global
B:built-in

所以,在你的情况下,它是E

蟒蛇2.x

在 python 2.x 中,你不能在 func 中修改这些变量

class A:
    def meth(self):
        foo=1
        bar=2
        def func():
            foo=2     # if you place this statement below the print statement then you'll get
                      # UnboundLocalError: local variable 'foo' referenced before assignment
            print foo,bar
        func()    
        print (foo) #meth's foo is unchanged
a=A()
a.meth()

输出:

2 2 
1

python 3.x:用于nonlocal修改变量:

class A:
    def meth(self):
        foo=1
        bar=2
        def func():
            nonlocal foo,bar             
            print (foo,bar)
            foo=2               #changes meth's foo to 2
        func()    
        print (foo)
a=A()
a.meth()

输出:

1 2
2
于 2012-10-20T06:52:51.617 回答