将相同的模块导入不同的文件 [英] Importing the same modules in different files

查看:82
本文介绍了将相同的模块导入不同的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我已经编写了一组要在python文件中使用的类,并在脚本(或其他文件中的python代码)中使用了它们.现在,两个文件都需要导入一组模块.导入应该只包含一次还是包含在两个文件中?

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). Now both the files require a set of modules to be imported. Should the import be included only once, or in both the files ?

文件1: my_module.py .

import os

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

文件2:

import os
import my_module

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

list_ = m.list_of_directories

print os.getcwd()

我应该在两个文件中添加行import os吗?

Should I be adding the line import os to both the files ?

假设要导入许多模块,这对性能有何影响?另外,在这种情况下,是否可以一次导入并重新加载模块?

推荐答案

正在使用模块的每个文件,都必须导入该模块.每个模块都是其自己的名称空间.您在该文件中显式导入的内容在该名称空间中可用.因此,如果两个文件都需要os,则应将它们导入两个文件中.

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.

这篇关于将相同的模块导入不同的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆