从当前目录的父目录(python)的另一个子目录导入另一个模块 [英] Importing another module from another subdirectory of the current directory's parent directory (python)

查看:546
本文介绍了从当前目录的父目录(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.

我看过涉及放置 __ init__的解决方案.py 在每个文件夹中,但我仍然有点困惑,虽然没有python解释器那么多。

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.

现在假设 resource1.py 想要从 physics1.py中导入一个函数,或者实际上 Game 目录中的任何其他 .py 文件,我该怎么做所以?

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?

我从bin.physics.physics1导入函数尝试了,但显然这不起作用。

I've tried from bin.physics.physics1 import function but obviously that doesn't work.

感谢您的帮助。

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


推荐答案

使用正常导入机制是不可能的,除非你使 Game 一个包(即通过放一个 __ init__) 游戏目录中的.py 。 python相对导入系统仅在包中使用。它不是通过它们在目录结构中的位置来引用任意模块的通用系统。如果你把游戏作为一个包,那么你可以从..bin.physics.physics1导入函数

It is not possible with the normal import mechanism unless you make Game a package (i.e., by putting an __init__.py inside the Game directory). The python relative import system only works within packages. 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.

编辑:还请注意,相对导入不适用于作为主程序执行的脚本。如果您尝试直接运行 resource.py 并使用相对导入,则会出现在非程序包中尝试相对导入错误。如果从其他模块导入资源,它将起作用。这是因为相对导入系统基于执行模块的名称,当您直接运行脚本时,其名称为 __ main __ 而不是通常的命名。使用 __ package __ 关键字,如果你真的需要,但它可能有点棘手。

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. 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. It's possible to get around this using the __package__ keyword if you really need to, but it can be a bit tricky.

这篇关于从当前目录的父目录(python)的另一个子目录导入另一个模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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