简体   繁体   English

在不同的文件中导入相同的模块

[英]Importing the same modules in different files

Supposing I have written a set of classes to be used in a python file and use them in a script (or python code in a different file). 假设我编写了一组要在python文件中使用的类,并在脚本中使用它们(或者在不同的文件中使用python代码)。 Now both the files require a set of modules to be imported. 现在这两个文件都需要导入一组模块。 Should the import be included only once, or in both the files ? 导入是仅包含一次,还是同时包含在两个文件中?

File 1 : my_module.py . 文件1: my_module.py

import os

class myclass(object):
    def __init__(self,PATH):
        self.list_of_directories = os.listdir(PATH)

File 2 : 文件2:

import os
import my_module

my_module.m = myclass("C:\\User\\John\\Desktop")

list_ = m.list_of_directories

print os.getcwd()

Should I be adding the line import os to both the files ? 我应该将行import os添加到这两个文件中吗?

How does this impact the performance, supposing there are lots of modules to be imported ? 假设有很多模块需要导入,这对性能有何影响? Also, is a module ,once imported, reloaded in this case ? 另外,一个模块,一旦导入,在这种情况下重新加载?

Each file that you are using a module in, must import that module. 您使用模块的每个文件都必须导入该模块。 Each module is its own namespace. 每个模块都有自己的命名空间。 Things you explicitly import within that file are available in that namespace. 您在该文件名中明确导入的内容在该命名空间中可用。 Thus, if you need os in both files, you should import them in both files. 因此,如果在两个文件中都需要os ,则应在两个文件中导入它们。

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

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