def method(self, *args):
def function(*args):
#can this access all method's variables, data, etc.
答案 0 :(得分:1)
是的,你可以,因为python在查找变量时遵循以下查找规则:
<强> LEGB 强>:
L:local
E:enclosing
G:global
B:built-in
所以,在你的情况下,它是E
:
python 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