class Example:
def fun2(self):
self.fun1() # Notice the `self` keyword tells the interprter that
# we're looking for a function, `fun1`, that is relative to
# the same object (once a variable is declared as an Example
# object) where `fun2` lives.
def fun1(self):
print "fun1 has been called"
# fun1 has been called
现在fun1可以被fun2引用,因为fun2现在将查看类名称空间。我通过运行测试了这一点:
class Example:
def fun2(self):
fun1()
def fun1(self):
print "fun1 was called"
def fun1():
print "fun1 outside the class was called"
起初,原始代码中的函数调用
fun2
不起作用。它将抛出错误消息:NameError: global name fun1' is not defined
。是因为函数在调用之前必须声明吗?你知道吗不,是的结果表明抛出异常是因为
fun1
在fun2
的范围之外。了解名称空间是如何工作的,这将阐明异常,并回答发布的问题。你知道吗任何函数的名称空间首先是它自己的函数名称空间,然后是全局名称空间。默认情况下,它不包含“class”命名空间。但是,它确实(而且应该)有权访问类命名空间。要让函数知道它正在调用同一类中的函数,必须在调用函数之前使用
self
关键字。你知道吗那么,这是可行的:
现在
fun1
可以被fun2
引用,因为fun2
现在将查看类名称空间。我通过运行测试了这一点:如果没有
self
关键字,则输出为:因此,要回答这个问题,当python解释一个脚本时,它会预编译所有相关的名称空间。因此,所有函数都知道所有其他适当寻址的函数,从而使原始声明顺序不相关。你知道吗
相关问题 更多 >
编程相关推荐