Python 中的面向对象编程

问题描述 投票:0回答:1

以下代码错误地输出了 55。 有什么问题吗?

class Rectangle:
    def __init__(self, width, height):
        self.w = width
        self.h = height

    def area(self):
        return self.w * self.h

    def perimeter(self):
        return (self.w + self.h) * 2


class Square(Rectangle):
    def __init__(self, length):
        super().__init__(width=length, height=length)


class Triangle:
    def __init__(self, l, h):
        self.l = l
        self.h = h

    def area(self):
        return 0.5 * self.l * self.h


class Pyramid(Square, Triangle):    # multiple inheritance
    def __init__(self, base, height):
        Square.__init__(self, length=base)
        Triangle.__init__(self, l=base, h=height)

    def area(self):
        return Square.area(self) + 0.5 * Square.perimeter(self) * self.h


pyramid = Pyramid(3, 5)
print(pyramid.area())    # 3 * 3 + 0.5 * 3 * 4 * 5 = 39

我写了如下正确的代码。 但我希望 Square 对象继承自 Rectangle 对象。

class Square:
    def __init__(self, length):
        self.lenght = length

    def area(self):
        return self.lenght ** 2

    def perimeter(self):
        return 4 * self.lenght


class Triangle:
    def __init__(self, l, h):
        self.l = l
        self.h = h

    def area(self):
        return 0.5 * self.l * self.h


class Pyramid(Square, Triangle):    # multiple inheritance
    def __init__(self, base, height):
        Square.__init__(self, length=base)
        Triangle.__init__(self, l=base, h=height)
        print(Square.area(self))
        print(Square.perimeter(self))

    def area(self):
        return Square.area(self) + 0.5 * Square.perimeter(self) * self.h


pyramid = Pyramid(3, 5)
print(pyramid.area())
python object oop multiple-inheritance
1个回答
0
投票

Square.__init__
调用
Rectangle.__init__
并将
w
h
设置为相同的值 (3)。然后
Triangle.__init__
self.h
设置为 5。因此,当您的
Pyramid
尝试使用
Rectangle
方法计算尺寸时,它将使用 5 而不是 3(这是您期望的长度为 3 的正方形)。独立的
Square
方法没有这个问题,因为它们没有尝试使用
self.h
.

如果你想保护你的变量不受层次结构中其他类的影响,你可以在它们前面加上

__
(双下划线)。这将防止它们被其他试图使用相同属性名称的类意外破坏。

参见 Python 文档中的私有变量

© www.soinside.com 2019 - 2024. All rights reserved.