【发布时间】:2012-02-20 13:17:28
【问题描述】:
代码如下:
#a.py
ALL_FUNC = [bar, foo] #a list containing all the functions defined in this module
def bar():
pass
def foo():
pass
然后,我这样运行它: $蟒蛇a.py NameError: name 'bar' 没有定义
错误的意思是,bar在执行ALL_FUNC = [bar, foo]时没有定义。但是为什么解释器在模块中找不到函数bar呢?就因为bar是在ALL_FUNC之后定义的?
看这个,这是一个python类,
class A:
def __init__(self):
self.bar()
def bar(self):
pass
a = A()
显然,上面的代码会运行没有任何错误,但是A中的bar也是在它被访问的位置之后定义的(在__init__中),为什么self.bar()可以找到没有任何错误?
跟进
这是另一个模块,
#b.py
def bar():
print k #well, apparently this line will result in an error
def foo():
pass
if __name__ == '__main__':
foo()
然后这样运行,
$ python b.py
没有错误!为什么? bar 应该会导致错误,不是吗?就因为__main__中没有用到,所以没有检测到错误?但是bar的定义被执行了对吧?
【问题讨论】:
标签: python class module method-resolution-order