你能调用一个以前没有声明过的函数吗?

2024-04-23 19:47:14 发布

您现在位置:Python中文网/ 问答频道 /正文

这样行吗?你知道吗

class Example:
    def fun2(self):
        fun1()

    def fun1()
        print "fun1 has been called"

请注意,上面声明的fun2正在调用fun1。我感兴趣的是在类中以这种顺序调用函数时会发生什么。你知道吗

是否存在这样的情况:即使对函数的调用被正确地处理,函数也不会意识到另一个函数?你知道吗


Tags: 函数self声明exampledef情况感兴趣class
1条回答
网友
1楼 · 发布于 2024-04-23 19:47:14

起初,原始代码中的函数调用fun2不起作用。它将抛出错误消息:NameError: global name fun1' is not defined是因为函数在调用之前必须声明吗?

你知道吗不,是的结果表明抛出异常是因为fun1fun2的范围之外。了解名称空间是如何工作的,这将阐明异常,并回答发布的问题。你知道吗

任何函数的名称空间首先是它自己的函数名称空间,然后是全局名称空间。默认情况下,它不包含“class”命名空间。但是,它确实(而且应该)有权访问类命名空间。要让函数知道它正在调用同一类中的函数,必须在调用函数之前使用self关键字。你知道吗

那么,这是可行的:

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"

如果没有self关键字,则输出为:

fun1 outside the class was called

因此,要回答这个问题,当python解释一个脚本时,它会预编译所有相关的名称空间。因此,所有函数都知道所有其他适当寻址的函数,从而使原始声明顺序不相关。你知道吗

相关问题 更多 >