Python继承在子级上添加新的init

2024-04-27 00:07:44 发布

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

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

I try someting like this, but still not work..

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) 

Tags: httpsselfcominitdefwidthlengthclass
1条回答
网友
1楼 · 发布于 2024-04-27 00:07:44

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

相关问题 更多 >