Python 从另一个文件导入类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41276067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Importing class from another file
提问by kemis
Before you mark it as duplicateplease read my problem:
在将其标记为重复之前,请阅读我的问题:
I am trying to import a class from a file from a subdirectory
我正在尝试从子目录的文件中导入一个类
> main.py
> --->folder/
> ----->file.py
and in file.py
i have a class imlpemented ( Klasa
)
What have I tried:
并且在file.py
我有一个班级实施(Klasa
)我试过什么:
putting in main.py:
放入main.py:
from folder import file
from file import Klasa
I am getting the error:
我收到错误:
from file import Klasa
ImportError: No module named 'file'
从文件导入 Klasa
导入错误:没有名为“文件”的模块
When I try to use just:
当我尝试仅使用:
from folder import file
I get this error:
我收到此错误:
tmp = Klasa()
NameError: name 'Klasa' is not defined
tmp = Klasa()
NameError:未定义名称“Klasa”
I have put an empty __init__.py
in the subfolder and it still does not work, and I have put in the __init__.py
: from file import Klasa
and still doesnt work.
我__init__.py
在子文件夹中放了一个空的,但它仍然不起作用,我已经放入了__init__.py
:from file import Klasa
但仍然不起作用。
If main and file are in the same folder this work:
如果 main 和 file 在同一文件夹中,则此工作:
from file import Klasa
from file import Klasa
but i want them to be in separate files.
但我希望它们在单独的文件中。
Can someone tell me what i am doing wrong?
有人能告诉我我做错了什么吗?
回答by Right leg
Your problem is basically that you never specified the right path to the file.
您的问题基本上是您从未指定文件的正确路径。
Try instead, from your main script:
相反,从您的主脚本尝试:
from folder.file import Klasa
Or, with from folder import file
:
或者,使用from folder import file
:
from folder import file
k = file.Klasa()
Or again:
或者再次:
import folder.file as myModule
k = myModule.Klasa()