Python提升?

hko*_*ala 5 python

Python 中什么时候创建对象?它们是在解释变量声明行时创建的还是在执行开始时创建的?

Rap*_*Rap 3

当在 Python 脚本中遇到对象时,就会创建对象。Python 中没有任何东西被提升,没有变量,没有函数,什么都没有。

所以这不起作用:

print(foo())  # NameError: name 'foo' is not defined

def foo():
    return 'hello'
Run Code Online (Sandbox Code Playgroud)

虽然这确实:

def foo():
    return 'hello'

print(foo())  # 'hello'
Run Code Online (Sandbox Code Playgroud)