python中的OOP,以长方体类为例

2024-04-19 02:30:39 发布

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

我创建了一个类来计算python中矩形的面积和周长

我想扩展这个类,计算长方体的面积和体积

我的尝试如下

class Rectangle ():  
    def __init__(self, L, W):  
        self.length = L
        self.width = W

    def rect_perimeter(self):  
        return 2 * (self.length + self.width)

    def rect_area(self):  
        return self.length * self.width


class RectangularCuboid (Rectangle):  
    def __init__(self, H):  
        self.height = H
        Rectangle.__init__ (self, L, W)  

    def rect_area(self):  
        return 2 * (self.length * self.width + self.width * self.height + self.height * self.lenght)

    def rect_volume(self):  
        return self.length * self.width * self.height

RC = RectangularCuboid(30, 20, 10)
R = Rectangular(30,20)
RC.rect_area()
RC.rect_volume()
print('Rectangle Cuboid Area:', RC.rect_area(), ', Rectangle Cuboid Volume:', RC.rect_volume())

但是我得到了以下错误

Traceback (most recent call last):
  File "C:/Users/User/.PyCharmCE2019.3/config/scratches/scratch.py", line 24, in <module>
    RC = RectangularCuboid(30, 20, 10)
TypeError: __init__() takes 2 positional arguments but 4 were given

Process finished with exit code 1

我错过了什么


Tags: rectselfreturninitdefareawidthlength
1条回答
网友
1楼 · 发布于 2024-04-19 02:30:39
class Rectangle ():  
    def __init__(self, L, W):  
        self.length = L
        self.width = W

    def rect_perimeter(self):  
        return 2 * (self.length + self.width)

    def rect_area(self):  
        return self.length * self.width


class RectangularCuboid (Rectangle):  
    def __init__(self, H,L,W):  
        self.height = H
        self.length = L
        self.width = W

    def rect_area(self):  
        return 2 * (self.length * self.width + self.width * self.height + self.height * self.length)

    def rect_volume(self):  
        return self.length * self.width * self.height


RC = RectangularCuboid(30,20, 10)

RC.rect_area()
RC.rect_volume()
print('Rectangle Cuboid Area:', RC.rect_area(), ', Rectangle Cuboid Volume:', RC.rect_volume())

这应该行得通 RectangleArcuboid继承自Rectangle,但init被重写,因此需要根据需要对其进行调整

相关问题 更多 >