【问题标题】:Python 3 InheritancePython 3 继承
【发布时间】:2023-03-25 05:57:01
【问题描述】:

我是 OOP 的初学者,一直在尝试使用 Python3 自学其中的一些概念。但是,我已经被继承困住了。这是我的源代码:

#! /usr/bin/env python3

class TwoD:
    def __init__(self, height, width):
    self.h = height
    self.w = width
def perimeter(self, height, width):
    return 2 * (height + width)
def area(self, height, width):
    return height * width

class Cuboid(TwoD):
def __init__(self, height, width, depth):
    self.d = depth
def volume(self, height, width, depth):
    return height * width * depth

x = Cuboid(3, 4, 5)
print(x.volume())
print(x.perimeter())
print(x.area())

我运行它时遇到的错误如下。读起来好像我需要为卷添加参数,但 x 不是为它提供了所需的变量吗?

Traceback (most recent call last):
File "./Class.py", line 19, in <module>
print(x.volume())
TypeError: volume() missing 3 required positional arguments: 'height', 'width', and 'depth'

所以有人可以让我知道我做错了什么。我敢肯定这很愚蠢。另外,有人可以解释一下我将如何在 Python3 中使用多重继承吗?

提前致谢

【问题讨论】:

  • 请将所有标签替换为 4 个空格。

标签: class oop inheritance python-3.x multiple-inheritance


【解决方案1】:

由于您在__init__() 方法中创建了两个数据属性 self.hself.w,您可以在其他方法中使用它们,因此无需传递任何参数:

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

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

另外,在Cuboid 类的__init__() 方法中不要忘记调用super,所以self.hself.w 成为数据属性

【讨论】:

    【解决方案2】:

    看起来好像我需要向音量添加参数,但不是 x 为其提供所需的变量?

    是的,确实如此,这意味着您根本不应该在方法定义中包含它们:

    class TwoD:
        def __init__(self, height, width):
            self.h = height
            self.w = width
        def perimeter(self):
            return 2 * (self.h + self.w)
        def area(self):
            return self.h * self.w
    

    等等。所以实际上问题不是继承,而是你的代码根本不是面向对象的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-10
      • 1970-01-01
      • 2014-01-07
      • 2018-08-26
      • 2019-12-01
      • 2019-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多