简体   繁体   English

从当前目录的父目录的另一个子目录导入另一个模块(python)

[英]Importing another module from another subdirectory of the current directory's parent directory (python)

I'm attempting to write a game. 我正在尝试写游戏。 I therefore have lots of different types of code and want to arrange them in a useful hierarchy. 因此,我有很多不同类型的代码,并希望将它们排列在有用的层次结构中。

I've looked at solutions that involve placing __init__.py in each folder but I'm still somewhat confused, though not as much as the python interpreter. 我看过涉及在每个文件夹中放置__init__.py解决方案,但我仍然有些困惑,尽管不如python解释器那么多。

Now suppose resource1.py wants to import a function from physics1.py , or indeed any other .py file in the Game directory, how would I go about doing so? 现在假设resource1.py想从physics1.pyGame目录中的任何其他.py文件导入一个函数,我该怎么做?

I've tried from bin.physics.physics1 import function but obviously that doesn't work. 我已经尝试过from bin.physics.physics1 import function但是显然不起作用。

Thanks for your help. 谢谢你的帮助。

/Game
    launcher.py
    /bin
        game.py
        __init__.py
        /physics
            __init__.py
            physics1.py
            physics2.py
    /resources
        __init__.py
        resource1.py

It is not possible with the normal import mechanism unless you make Game a package (ie, by putting an __init__.py inside the Game directory). 除非您将Game打包(例如,通过将__init__.py放入Game目录中),否则通常的导入机制是不可能的。 The python relative import system only works within packages . python相对导入系统仅在package中起作用。 It is not a general system for referring to arbitrary modules by their location in the directory structure. 它不是通过目录结构中的任意模块引用任意模块的通用系统。 If you make Game a package, then you could do from ..bin.physics.physics1 import function . 如果将Game打包,则可以from ..bin.physics.physics1 import function

Edit: Note also that relative imports don't work from a script executed as the main program. 编辑:还请注意,相对导入不适用于作为主程序执行的脚本。 If you try to run resource.py directly and it uses relative imports, you'll get a "relative import attempted in non-package" error. 如果您尝试直接运行resource.py并使用相对导入,则会收到“尝试在非程序包中进行相对导入”错误。 It will work if you import resource from another module. 如果您从另一个模块导入资源,它将起作用。 This is because the relative import system is based on the "name" of the executing module, and when you run a script directly its name is __main__ instead of whatever it would usually be named. 这是因为相对导入系统基于执行模块的“名称”,并且当您直接运行脚本时,其名称为__main__而不是通常使用的名称。 It's possible to get around this using the __package__ keyword if you really need to, but it can be a bit tricky. 如果确实需要,可以使用__package__关键字解决此问题,但这可能有些棘手。

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

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