Skip to main content
 首页 » 编程设计

python之Python 是否在我的 'from Bla import bla' 语句中引用相同的实例

2025年05月04日12jpfss

假设我有以下伪代码。在两个文件中导入 bla 是指 Bla 的 2 个实例还是它们指的是同一个实例?换句话说,我可以像这样在 Python 中连接和断开不同文件中的单个连接吗?

bla.py

import socket 
class Bla: 
  connect(self): 
    self.connection = socket.socket(...) 
  disconnect(self): 
    self.connection.close() 
bla = Bla() 

你好.py

from bla import bla 
bla.connect() 

世界.py

from bla import bla 
bla.disconnect() 

请您参考如下方法:

是的,在 hello 和 world 中,bla 都引用相同的实例。

模块是单例,它们的命名空间只有一个副本。顶层语句(函数和生成器之外的所有内容)仅在第一次导入模块时执行一次。

模块在 sys.modules mapping 中管理.导入首先确保模块被加载并出现在 sys.modules 中,之后名称被绑定(bind)到导入命名空间中。本质上,from bla import bla 与 bla = sys.modules['bla'].bla 赋值语句的作用相同。因此,将您的模块加载到内存中只发生一次,您的 bla = Bla() 只执行一次,所有进一步的导入都将访问该实例的引用。

来自import statement documentation :

The basic import statement (no from clause) is executed in two steps:

  1. find a module, loading and initializing it if necessary
  2. define a name or names in the local namespace for the scope where the import statement occurs.

[...]

The from form uses a slightly more complex process:

  1. find the module specified in the from clause, loading and initializing it if necessary;
  2. for each of the identifiers specified in the import clauses:
    1. check if the imported module has an attribute by that name
    2. if not, attempt to import a submodule with that name and then check the imported module again for that attribute
    3. if the attribute is not found, ImportError is raised.
    4. otherwise, a reference to that value is stored in the local namespace, using the name in the as clause if it is present, otherwise using the attribute name

(大胆强调我的)。