Python继承为子代添加新的init

时间:2018-11-19 13:17:04

标签: python inheritance

https://pastebin.com/GyPzN8Yz

我想从TwoDim类开始并计算体积,而无需重复定义长度和宽度,也无需创建TwoDim实例,而是直接创建ThreeDim。

class TwoDim():
    def __init__(self, length, width):
        self.length = length
        self.width = width
        self.square = self.length * self.width

class ThreeDim(TwoDim):
    def __init__(self, height):
        self.height = height
        self.volume = self.square * self.height
  

我尝试像这样的方法,但仍然无法正常工作。

class TwoDim(): 
    def __init__(self, length, width): 
        self.length = length 
        self.width = width 
        self.square = self.length * self.width 

class ThreeDim(TwoDim): 
    def __init__(self, length, width, height): 
        super().__init__(self, length, width, height) 
        self.height = height 
        self.volume = self.square * self.height 

block = ThreeDim(length = 10, width = 5, height = 4) 

1 个答案:

答案 0 :(得分:1)

Python 3:

class ThreeDim(TwoDim):
    def __init__(self, length, width, height):
        super().__init__(length, width)
        self.height = height
        self.volume = self.square * self.height

Python 2:

class ThreeDim(TwoDim, object):
    def __init__(self, length, width, height):
        super(ThreeDim, self).__init__(length, width)
        self.height = height
        self.volume = self.square * self.height

或:

class TwoDim(object):
    def __init__(self, length, width):
        self.length = length
        self.width = width
        self.square = self.length * self.width

class ThreeDim(TwoDim):
    def __init__(self, length, width, height):
        super(ThreeDim, self).__init__(length, width)
        self.height = height
        self.volume = self.square * self.height

({classes need to inherit from object to use super(),这就是python3语法更容易的原因之一。)

别忘了TwoDim上的self参数:

class TwoDim():
    def __init__(self, length, width):
        self.length = length
        self.width = width
        self.square = self.length * self.width