Python类导入错误
我正在研究python中的类和OO,在尝试从包导入类时发现了一个问题。项目结构和类别如下所述:Python类导入错误,python,class,import,Python,Class,Import,我正在研究python中的类和OO,在尝试从包导入类时发现了一个问题。项目结构和类别如下所述: ex1/ __init__.py app/ __init__.py App1.py pojo/ __init__.py Fone.py 课程包括: 火锅 class Fone(object): def __init__(self,volume): self.change_volume(v
ex1/
__init__.py
app/
__init__.py
App1.py
pojo/
__init__.py
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)
当我尝试从ex1.pojo import Fone使用时,出现以下错误:
fone = Fone(70)
TypeError: 'module' object is not callable
但是当我使用ex1.pojo.Fone import*中的时,程序运行良好
为什么我不能用我编码的方式导入Fone类?在python中,您可以导入模块或该模块的成员
from ex1.pojo.Fone import Fone
当您这样做时:
从ex1.pojo导入Fone
您正在导入模块Fone
,以便使用
fone=fone.fone(6)
或该模块的任何其他成员
但您也只能导入该模块的某些成员,如
从ex1.pojo.Fone导入Fone
我认为有必要回顾一些关于python模块、包和导入的内容您应该导入类,而不是模块。例如:
from ex1.pojo.Fone import Fone
您还应该为模块名使用小写命名约定。hmm,奇怪。我认为模块的导入在语法上等同于类的导入。这让我很困惑,因为我习惯于用Java构造类,但Python将.py文件视为模块capitalized@AndréCaldas是的,在python中,您的模块可以包含多个类,或者多个函数或用于在Java中构造类的mixI,所以我认为模块的名称应该大写,就像Java一样。但我很喜欢你关于公约的建议!
from ex1.pojo.Fone import Fone