如何导入模块?

2024-06-20 11:46:26 发布

您现在位置:Python中文网/ 问答频道 /正文

/projects/mymath$ ls
__init__.py  __init__.pyc  mymath.py  mymath.pyc  tests

tests目录下

^{pr2}$

我试图导入我的阶乘函数

sys.path.insert(0,"../../")
#import mymath
from mymath.MyMath import factorial

但上面说没有一个模块叫MyMath。在

这是我的虚拟MyMath类。在

class MyMath(object):

        def factorial(self, number):
                if n <= 1:
                        return 1
                else:
                        return n * factorial(n-1)

怎么了?谢谢。这是否是一个好的实践(编辑sys路径?)在

这将有效import mymath


Tags: 函数pyimport目录returninitsystests
3条回答

不能从类中导入函数。您想要导入类本身(import mymath.mymath.MyMath),或者将函数放在模块级别并执行import mymath.mymath.factorial。在

据我所知,这是对的。没有名为mymath.MyMath的模块。有一个名为mymath.mymath的模块。。。在

明确地说,当您创建一个文件夹并在其中放入一个__init__.py文件时,您已经装箱了一个包。如果您的__init__.py文件为空,那么您仍然必须显式导入包中的模块。因此,您必须执行import mymath.mymathmymath模块导入到您的命名空间中。然后您可以通过mymath.mymath.MyMath等方式访问您想要的东西。如果要直接导入类,则必须执行以下操作:

from mymath.mymath import MyMath

正如其他人已经解释过的,您不能从类中导入方法。你必须导入整个类。在

一个问题是你的进口是错误的。你有一个名为mymath的包和一个名为mymath的模块。在那个模块中是一个类。这是您最多可以导入的:

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

另一个问题是您对factorial的第二次调用应该在self上调用factorial,否则它将尝试将其作为模块中的一个自由函数查找,这将不起作用。试试看!在

相关问题 更多 >