Python导入 [英] Python importing

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

问题描述

我有一个文件myfile.py,它从file.py导入Class1,并且file.py包含对file2.pyfile3.pyfile4.py的不同类的导入.

I have a file, myfile.py, which imports Class1 from file.py and file.py contains imports to different classes in file2.py, file3.py, file4.py.

在我的myfile.py中,我可以访问这些类吗?还是需要再次导入file2.py,file3.py等?

In my myfile.py, can I access these classes or do I need to again import file2.py, file3.py, etc.?

Python是否会自动添加我导入的文件中包含的所有导入,并且我可以自动使用它们吗?

Does Python automatically add all the imports included in the file I imported, and can I use them automatically?

推荐答案

最佳实践是导入定义所需标识符的每个模块,并使用该模块名称通过限定的标识符;我建议仅在要导入的是软件包中的模块时才使用from.这个问题经常在SO上讨论.

Best practice is to import every module that defines identifiers you need, and use those identifiers as qualified by the module's name; I recommend using from only when what you're importing is a module from within a package. The question has often been discussed on SO.

从需要一个或多个moda定义的标识符的许多模块(例如modbmodcmodd,...)中导入一个模块,例如moda,不会降低您的速度down:moda的字节码仅加载一次(并且可能从其源代码构建,如果需要),第一次将moda导入任何地方,然后模块的所有其他导入都使用涉及缓存的快速路径( dict将模块名称映射到可以在需要的情况下通过sys.modules访问的模块对象...,如果您首先是import sys,当然!-).

Importing a module, say moda, from many modules (say modb, modc, modd, ...) that need one or more of the identifiers moda defines, does not slow you down: moda's bytecode is loaded (and possibly build from its sources, if needed) only once, the first time moda is imported anywhere, then all other imports of the module use a fast path involving a cache (a dict mapping module names to module objects that is accessible as sys.modules in case of need... if you first import sys, of course!-).

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

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