【问题标题】:Python function invoked before definition在定义之前调用的 Python 函数
【发布时间】:2014-03-06 17:24:40
【问题描述】:

我对下面给出的 Python 代码感到困惑,其中函数在定义之前被调用。是否可以?是不是因为函数没有返回值?

from Circle import Circle

def main():
    myCircle = Circle()
    n = 5
    printAreas(myCircle, n) #The function is called here

def printAreas(c, times):
    xxxx
    xxxx

main()

【问题讨论】:

  • 是什么让你认为函数在定义之前被调用?
  • 不是。它在 main 被调用时被调用,它位于程序的最后。
  • 尝试将调用移动到mainprintAreas的定义之前,如:main()<NEWLINE>def printAreas(...): ...

标签: python interpreter


【解决方案1】:

你的程序会发生什么:

  1. main 已定义,在其主体中引用了 printAreas — 请注意,这只是一个引用,而不是调用
  2. printAreas 已定义
  3. main 被调用
  4. main 致电printAreas

所以一切都很好——你可以在任何时候引用任何你想要的名字,只要你确保在包含引用的代码被执行时这些名字已经被定义(绑定到一个值) :

def foo():
    print bar  # reference to as-of-yet non-existent bar

# calling foo here would be an error

bar = 3

foo()  # prints 3

【讨论】:

    【解决方案2】:

    Python 将首先解析您的文件,将所有函数、变量等注册到全局命名空间中。它将然后调用main 函数,然后该函数将调用printAreas。当时,这两个函数都在您的脚本命名空间中,因此完全可以访问。

    让你困惑的只是阅读顺序。

    【讨论】:

      【解决方案3】:

      您在程序结束时调用main。这允许解释器加载您的所有函数,然后启动您的 main 函数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多