简体   繁体   English

Python 导入模块方法

[英]Python import module approaches

I have created a package named mod and placed a python file inside it (aka: module).我创建了一个名为 package 的 mod,并在其中放置了一个 python 文件(又名:模块)。 The name of the python file is printme.py. python 文件的名称是 printme.py。

I import the module in the below couple of ways.我通过以下几种方式导入模块。

import mod.printme 

 ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'mod']

After this is executed, the name space is appended with the value mod.执行此操作后,名称空间将附加值 mod。 I expected this to have the value printme (which is the actual module name)我希望它具有值 printme (这是实际的模块名称)

from mod import printme

['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'printme']

After this is executed, correctly the name space is appended with the value printme as expected.执行此操作后,名称空间正确地附加了预期的值 printme。

Technically, both are expected to import the module printme in the local namespace, I am little puzzled why the first approach is NOT placing the printme module name in the local namespace.从技术上讲,两者都应该在本地命名空间中导入模块 printme,我有点困惑为什么第一种方法不将 printme 模块名称放在本地命名空间中。

Could someone please help me to understand.有人可以帮助我理解。

Thanks!谢谢!

Assume mod to be a book and printme.py as a chapter.假设mod是一本书, printme.py是一章。

When you are commanding that import mod.printme you are saying to python "Hey. Please bring mod book and it's printme chapter as a whole book and remove other chapters".当您命令import mod.printme时,您是在对 python 说“嘿。请将 mod book 和它的 printme 章节作为整本书并删除其他章节”。 Now whenever you need to reference content from this book you need to say mod.printme.foo() as the name of your new book is mod and it has only one chapter printme .现在每当你需要引用这本书的内容时,你需要说mod.printme.foo()因为你的新书的名字是mod并且它只有一章printme

When you are commanding that from mod import printme you are saying: "Hey. Please bring print me chapter in mod book as a book in itself".当您from mod import printme命令时,您是在说:“嘿。请将 mod book 中的 print me chapter 作为一本书本身”。 Now whenever you need to reference content from this book you need to say printme.foo() as the chapter has become book so only name of book, in your case printme , is needed.现在,每当你需要引用本书的内容时,你需要说printme.foo()因为章节已经变成书了,所以只需要书名,在你的例子中是printme

And if you want Python to bring all headings of chapter printme in your current book (the book you are writing, as in Python each file is a module) you may use from mod.printme import * .如果你想 Python 将所有章节printme的标题带入你当前的书(你正在写的书,因为 Python 每个文件都是一个模块)你可以使用from mod.printme import * It will bring all headings only.它只会带来所有标题。 So you need not to reference the book/chapter , just foo() will work.所以你不需要参考书book/chapter ,只需要foo()就可以了。

They works this way because they are made to work this way.他们以这种方式工作,因为他们被要求以这种方式工作。

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

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