简体   繁体   English

在定义了 function 之后导入一个模块

[英]Importing a module after a function is defined

How does the following work in python:以下如何在 python 中工作:

def f(num):
    time.sleep(num)
    return num

>>> f(2)
NameError: name 'time' is not defined
>>> import time
>>> f(2)
2

How does python "insert" the module into that function, or how does the lookup mechanism work there as to be able to import something after the function is created? python 如何将模块“插入”到 function 中,或者在创建 function 后查找机制如何工作以便能够导入某些内容?

Unlike a compiler, which statically binds names to fixed addresses at compilation time, Python code is executed by an interpreter that resolves names at runtime, so what the name time refers to is not resolved by the interpreter until the execution runs into an expression that actually references it, at which point the interpreter will follow the name resolution rules to resolve the name into an object.与在编译时将名称静态绑定到固定地址的编译器不同,Python 代码由在运行时解析名称的解释器执行,因此名称time所指的内容不会由解释器解析,直到执行运行到实际的表达式引用它,此时解释器将遵循名称解析规则将名称解析为 object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM