[英]Python import on sub-folders
It`s been a while since I create my classes and import them to my script, using自从我创建我的类并将它们导入我的脚本以来已经有一段时间了,使用
from <folder> import <file>
and my file.py looks like this:我的 file.py 看起来像这样:
class myClass:
def __init__():
and so on.等等。
However, whenever I want to use this class on my main script, I have to do:但是,每当我想在我的主脚本上使用这个 class 时,我都必须这样做:
file.myClass()
Is thera a better way so I could use only "myClass()"?是否有更好的方法让我只能使用“myClass()”?
I have recreated the scenario with the following directory structure:我用以下目录结构重新创建了场景:
.
├── outer.py
└── some_folder
└── inner.py
You missed the self
in __init__
method:你错过了__init__
方法中的self
:
some_folder/inner.py
: some_folder/inner.py
:
class myClass:
def __init__(self):
print("myClass is initiated")
Import the class from the file when you want to directly use the class name.当你想直接使用class名称时,从文件中导入class。
outer.py
: outer.py
:
from some_folder.inner import myClass
some_object = myClass()
Output: Output:
myClass is initiated
Instead of importing the file, you can import the class您可以导入 class 而不是导入文件
from package.module import MyClass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.