如何导入类名python [英] How to import class name python
问题描述
这是我的python文件夹结构(它没有任何python包):
Here is my python folder structure (it does not have any python package):
folder/
script1.py
script2.py
script1具有:
script1 has:
class myclass(object):
def __init__():
print("in init")
def showReport():
print("in report only function")
script2具有:
script2 has:
from . import myclass
当我运行python -m folder.script2
and when I run python -m folder.script2
我得到/usr/bin/python: cannot import name myclass
如何导入此类,以便可以在script2上从此类调用函数?
How can I import this class so that I can call functions from this class on script2?
推荐答案
您说您确实有一个软件包,但是您仍然必须引用包含类myclass
的 module script1
,所以:
You say you do have a package, but you still have to reference the module script1
that contains your class myclass
, so:
from .script1 import myclass
P.S.在Python中,习惯上将驼峰式用作类名,因此MyClass
而不是myclass
P.S. In Python it's customary to use camel case for class names, so MyClass
not myclass
使用名为package
的软件包以及模块module1
和module2
的工作示例,然后从外部package
调用python -m package.module2
:
Working example with a package called package
and modules module1
and module2
, then from outside package
, I call python -m package.module2
:
➜ ~ tree package
├── __init__.py
├── module1.py
└── module2.py
➜ ~ cat package/module1.py
class MyClass(object):
def work(self):
print 'Working!'
➜ ~ cat package/module2.py
from .module1 import MyClass
if __name__ == '__main__':
worker = MyClass()
worker.work()
➜ ~ python -m package.module2
Working!
这篇关于如何导入类名python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!