这就是您调用时会发生的情况Cone.__init__()
:
- 它执行
Cylinder.__init__()
,
- 它依次调用
self.calcVolume()
,
- 因为继承,解析顺序在
Cone
类型上找到方法,
- 它调用
Cone.calcVolume()
而不是Cylinder.calcVolume()
.
在__init__()
我想你想打电话:
Cone.calcVolume(self)
在Cone.__init__()
, 或
Cylinder.calcVolume(self)
在Cylinder.__init__()
.
当然,如果您使用的是新样式类(继承自object
),那么您可以使用type(self).calcVolume(self)
; 但是type(self)
,在旧式课程上,将为您提供instance
类型而不是实际课程,这在您的情况下不起作用。
完整示例:
class Circle():
#Constructor
def __init__ (self, radius):
self.__radius = radius
self.calcArea()
def calcArea(self, PI = 3.14):
self.__area = (self.__radius**2) * PI
#Get Functions
def GetArea(self):
return self.__area
def GetRadius(self):
return self.__radius
#Set Functions
def SetRadius(self, radius):
self.__radius = radius
self.calcArea()
class Cylinder():
#Constructor
def __init__(self, radius, height):
self.__height = height
self.__base = Circle(radius)
Cylinder.calcVolume(self)
def calcVolume(self):
self.__volume = self.__base.GetArea() * self.__height
#Get Functions
def GetVolume(self):
return self.__volume
def GetBase(self):
return self.__base
def GetRadius(self):
return self.__base.GetRadius()
def GetHeight(self):
return self.__height
#Set Functions
def SetRadius(self, radius):
self.__base.SetRadius(radius)
self.calcVolume()
def SetHeight(self, height):
self.__height = height
self.calcVolume()
class Cone(Cylinder):
#Constructor
def __init__ (self, radius, height):
Cylinder.__init__(self, radius, height)
Cone.calcVolume(self)
def calcVolume(self):
Cylinder.calcVolume(self)
self.__volume = Cylinder.GetVolume(self) * (1.0/3.0)
#Get Functions
def GetVolume(self):
return self.__volume
#Set Functions
def SetRadius(self, radius):
Cylinder.SetRadius(self, radius)
self.calcVolume()
def SetHeight(self, height):
Cylinder.SetHeight(self, height)
self.calcVolume()
def main():
cylinder = Cylinder(5, 6)
cone = Cone(5, 6)
circle = Circle(5)
print cylinder.GetVolume()
print cone.GetVolume()
print circle.GetArea()
cone.SetHeight(7)
print cone.GetVolume()
main()