Python类导入错误

And*_*das 2 python import class

我正在研究python中的类和OO,尝试从包中导入类时发现了一个问题。项目结构和类描述如下:

ex1/
    __init__.py
    app/
        __init__.py
        App1.py
    pojo/
        __init__.py
        Fone.py
Run Code Online (Sandbox Code Playgroud)

这些课程:

Fone.py

class Fone(object):

    def __init__(self,volume):
        self.change_volume(volume)

    def get_volume(self):
        return self.__volume

    def change_volume(self,volume):
        if volume >100:
            self.__volume = 100
        elif volume <0:
            self.__volume = 0
        else:
            self.__volume = volume

volume = property(get_volume,change_volume)
Run Code Online (Sandbox Code Playgroud)

App1.py

from ex1.pojo import Fone

if __name__ == '__main__':
    fone = Fone(70)
    print fone.volume

    fone.change_volume(110)
    print fone.get_volume()

    fone.change_volume(-12)
    print fone.get_volume()

    fone.volume = -90
    print fone.volume

    fone.change_volume(fone.get_volume() **2)
    print fone.get_volume()
Run Code Online (Sandbox Code Playgroud)

当我尝试从ex1.pojo import Fone使用时,引发以下错误:

fone = Fone(70)
TypeError: 'module' object is not callable
Run Code Online (Sandbox Code Playgroud)

但是,当我从ex1.pojo.Fone import *使用时,程序运行正常。

为什么我不能以编码方式导入Fone类?

dm0*_*514 5

在python中,您可以导入模块或该模块的成员

当您这样做时:

from ex1.pojo import Fone

您正在导入模块,Fone以便可以使用

fone = Fone.Fone(6)

或该模块的任何其他成员。

但是您也只能导入该模块的某些成员,例如

from ex1.pojo.Fone import Fone

我认为值得回顾一些有关python模块,包和导入的文档