/projects/mymath$ ls
__init__.py __init__.pyc mymath.py mymath.pyc tests
and under the directory tests I have
/projects/mymath/tests/features$ ls
steps.py steps.pyc zero.feature
I tried to import my factorial function
sys.path.insert(0,"../../")
#import mymath
from mymath.MyMath import factorial
But it said No module named MyMath.
Here is my dummy MyMath class.
class MyMath(object):
def factorial(self, number):
if n <= 1:
return 1
else:
return n * factorial(n-1)
So what’s wrong? Thanks. Is this even a good practice (editing the sys path?)
This will work import mymath
From what I can tell, it’s right. There is no module named
mymath.MyMath. There’s a module namedmymath.mymaththough…To be explicit, when you create a folder and put an
__init__.pyfile in it, you’ve crated a package. If your__init__.pyfile is empty, then you still have to explicitly import the modules in the package. So you have to doimport mymath.mymathto import themymathmodule into your namespace. Then you can access the things you want viamymath.mymath.MyMath, and so on. If you want to import the class directly in, you have to do this:And as someone else has already explained, you can’t import a method from a class. You have to import the whole class.