简体   繁体   English

从Python中的导入语句

[英]from import statements in Python

I'm a little confused by the from import statements in Python. 我对Python中的from import语句感到有些困惑。 In particular, how I can import a class from a module that is within a package. 特别是,我如何从包中的模块导入类。 For example, if I have a package named my package that has two modules (module 1 and module 2), how can I import a specific class from module 1 within module 2? 例如,如果我有一个名为my package的包有两个模块(模块1和模块2),我如何从模块2中的模块1导入特定的类?

What I'm finding currently is that I need to (within module two) do the following... 我现在发现的是我需要(在模块二中)做以下事情......

from package import module1
module1.class1()

While this works, I'd much rather be able to access class1() directly from module 2 as it is not very readable . 虽然这有效,但我更愿意直接从模块2访问class1(),因为它不是非常易读。 However, the following syntax doesn't work... 但是,以下语法不起作用...

from package import module1.class1

Also, it won't let me simply go... 此外,它不会让我只是去...

from module1 import class1

How does one import a class which is in a module within a package, directly within a separate module within that package? 如何直接在该包中的单独模块内导入包内模块中的类?

You were on the right track: 你走在正确的轨道上:

from package.module1 import class1

If as you say you're importing from within the same package, you can also do 如果你说你是在同一个包装内进口,你也可以这样做

from .module1 import class1

The . . means "the position in the package hierarchy of the module doing the importing". 表示“执行导入的模块在程序包层次结构中的位置”。 See the documentation for info. 有关信息,请参阅文档

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

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