Here is my python folder structure (it does not have any python package):
folder/
script1.py
script2.py
script1 has:
class myclass(object):
def __init__():
print("in init")
def showReport():
print("in report only function")
script2 has:
from . import myclass
and when I run python -m folder.script2
I get /usr/bin/python: cannot import name myclass
How can I import this class so that I can call functions from this class on script2?
解决方案
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. In Python it's customary to use camel case for class names, so MyClass not myclass
Example
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!