2

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?

Marco
  • 1,377
  • 15
  • 18
codec
  • 7,978
  • 26
  • 71
  • 127

2 Answers2

3

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!
bakkal
  • 54,350
  • 12
  • 131
  • 107
  • Thanks. I got ` /usr/bin/python: No module named script1` – codec May 13 '16 at 07:15
  • I am running this script from outside of package python -m folder.script2. FYI. Here I dont have any __init__.py – codec May 13 '16 at 07:19
  • ok there was a spelling mistake import worked! but when I try to call a function using myClass.showReport()` I get `TypeError: unbound method showReport() must be called with myClass instance as first argument (got nothing instead)` – codec May 13 '16 at 07:28
  • You didn't instantiate the class, use `x = myClass()` not `x = myClass`, before calling `x.showReport()`, also you need `def showReport(self)`, you forgot `self` in your question. Please copy paste my **working** example then adapt it, you are dealing with many problems simultaneously it will be confusing. – bakkal May 13 '16 at 07:29
  • BTW I notice that though my script runs succesfully I get /usr/bin/python: No module named folder.script2.py at the end. – codec May 13 '16 at 07:38
  • No module named `folder.script2.py` the module name is `folder.script2` – bakkal May 13 '16 at 07:39
  • ok yeah by mistake I was running `python -m folder.script2.py` – codec May 13 '16 at 07:42
2

Try with from script1 import myclass

Dovi
  • 833
  • 1
  • 10
  • 29