简体   繁体   中英

How do I import my module?

/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

You can't import a function out of a class. You want to either import the class itself ( import mymath.mymath.MyMath ) or put the function at a module level and do import mymath.mymath.factorial .

From what I can tell, it's right. There is no module named mymath.MyMath . There's a module named mymath.mymath though...

To be explicit, when you create a folder and put an __init__.py file in it, you've crated a package. If your __init__.py file is empty, then you still have to explicitly import the modules in the package. So you have to do import mymath.mymath to import the mymath module into your namespace. Then you can access the things you want via mymath.mymath.MyMath , and so on. If you want to import the class directly in, you have to do this:

from mymath.mymath import MyMath

And as someone else has already explained, you can't import a method from a class. You have to import the whole class.

One problem is your import is wrong. You have a package called mymath, and a module in it called mymath. In that module is a class. That's the most you can import:

>>> from mymath.mymath import MyMath
>>> myMathObject = MyMath()
>>> myMathObject.factorial(5)
120

The other problem is your second call to factorial should call factorial on self , otherwise it will try to look it up as a free function in the module, which won't work. Try it!

Here is my dummy MyMath class.

Python is not Java; the class is not any kind of organizational unit here, but simply a blueprint for data types. There is no reason to define a class here (which would then have to be instantiated anyway); just define the factorial function as a function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM