【问题标题】:Can you call a function that has not been previously declared? [closed]你能调用一个之前没有声明过的函数吗? [关闭]
【发布时间】:2013-12-22 15:53:07
【问题描述】:

这行得通吗?

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

    def fun1()
        print "fun1 has been called"

请注意,fun2(在 fun1 上方声明)正在调用 fun1。我有兴趣了解在类中按此顺序调用函数时会发生什么。

是否存在某个函数不知道另一个函数的情况,即使对该函数的调用会被正确处理?

【问题讨论】:

  • @thefourtheye 你错过了问题的重点。课堂上应该有一个fun1。另外,我认为这不是functional 问题,因为类命名空间与问题相关。
  • 已更新。请立即查看
  • 您的实际问题是什么?您是否尝试过...运行您要询问的代码?我们不是您的翻译。

标签: python function syntax


【解决方案1】:

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

没有。原来抛出异常是因为fun1fun2的范围之外。了解命名空间的工作原理将阐明异常并回答发布的问题。

任何函数的命名空间首先是它自己的函数命名空间,然后是全局命名空间。默认情况下,它不包含“类”命名空间。但是,它确实(并且应该)可以访问类命名空间。要让函数知道它正在调用同一个类中的函数,必须在调用函数之前使用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 解释一个脚本时,它会预编译所有相关的命名空间。因此,所有函数都知道所有其他被适当寻址的函数,从而使原始声明顺序无关紧要。

【讨论】:

  • 您的部分回答让我认为fun1 旨在成为问题代码中类主体的一部分。是这样吗?
  • @delnan 是的。这是正确的。它已被重新编辑。
猜你喜欢
  • 2019-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-19
  • 1970-01-01
  • 2019-05-21
  • 2013-10-23
相关资源
最近更新 更多