为什么我可以在不使用全局变量的情况下在以下函数中使用类的实例?
class TestClass:
def __init__(self, name):
self.name = name
def MyName(self):
print "My name is: " + self.name
def testFunc():
# why can I use the instance here?
print "in testFunc()"
instance.MyName()
if __name__ == '__main__':
instance = TestClass("abc")
print "in __main__"
instance.MyName()
testFunc()
答案 0 :(得分:2)
在Python中有这样的规则,只要您不尝试分配它们,就可以从函数访问全局名称而不使用global
。也就是说,它们是只读的。只有在您要分配全局名称时才需要global
。
基本原理是分配全局名称是不明确的:它可能意味着创建本地名称或分配给全局名称。根据是否已定义全局名称是一个坏主意,因此global
关键字实际上解决了歧义。
但是,在没有分配之前读取名称并不是那么模糊:它可能是全局名称,也可能是错误。因此,假设全球一个没有坏处。
请注意,在没有全局的情况下使用只读名称,然后分配给它,是一个错误。
g = 1
def foo1():
g = 2 #local name
def foo2():
global g
g = 2 #global name
def foo3():
print(g) #global name
def foo4():
print(g) #global name
g = 2 # error!
答案 1 :(得分:1)
我想你想要这个:
class TestClass():
def foo():
pass
def test_func():
instance.foo()
def main():
instance = TestClass
test_func()
if __name__ == '__main__':
main()
给出了这个错误:
$ python test.py
Traceback (most recent call last):
File "test.py", line 13, in <module>
main()
File "test.py", line 10, in main
test_func()
File "test.py", line 6, in test_func
instance.foo()
NameError: name 'instance' is not defined
你看到了区别吗?
答案 2 :(得分:1)
testFunc
首先搜索其本地空间: -
print locals() #in testFunc.
output:-{}
,然后搜索其全球空间。
在`testFunc中尝试print globals
它有
`'instance': <__main__.TestClass instance at 0x7f859aca64d0>`.`
因此instance
中可以访问testFunc
。
python遵循LEGB
规则,因此搜索如下: -
的 1:-Locals
2:-Enclosing
3:-GLobals
4:-Builitins 强>
答案 3 :(得分:1)
在Python中,可以从任何范围通过名称访问全局变量。您的test_func()
函数可以按名称引用 instance
,因为它已绑定在全局范围内,即if __name__ == '__main__'
块中。
当您想要从本地范围绑定全局名称时,global
关键字非常有用。为此,您声明global foo
然后绑定它,例如foo = 1
,来自本地范围。
总结:当引用时,不需要名称为global
的全局变量。 绑定全局变量时,需要global
。