Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Class Python3继承_Class_Oop_Inheritance_Python 3.x_Multiple Inheritance - Fatal编程技术网

Class Python3继承

Class Python3继承,class,oop,inheritance,python-3.x,multiple-inheritance,Class,Oop,Inheritance,Python 3.x,Multiple Inheritance,我是OOP的初学者,一直在尝试使用Python3自学OOP的一些概念。然而,我一直被遗产所困扰。这是我的源代码: #! /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(s

我是OOP的初学者,一直在尝试使用Python3自学OOP的一些概念。然而,我一直被遗产所困扰。这是我的源代码:

#! /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())
我运行它时得到的错误如下。它读起来好像我需要向volume添加参数,但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'
回溯(最近一次呼叫最后一次):
文件“/Class.py”,第19行,在
打印(x.volume())
TypeError:volume()缺少3个必需的位置参数:“高度”、“宽度”和“深度”
有人能告诉我我做错了什么吗。我肯定这是件愚蠢的事。另外,有人能解释一下我将如何在Python3中使用多重继承吗


提前感谢

因为在
\uuu init\uuuu()
方法中,您正在创建两个数据属性
self.h
self.w
,您可以在其他方法中使用它们,因此不需要传递任何参数:

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

def area(self):
    return self.h * self.w
另外,在
长方体
类的
\uuuu init\uuuu()方法中,不要忘记调用
super
,因此
self.h
self.w
成为数据属性

它读起来好像我需要向卷添加参数,但不需要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'
是的,确实如此,这意味着您根本不应该在方法定义中包含它们:

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

等等。因此,事实上,问题不在于继承,而在于您的代码根本不是面向对象的。

请用4个空格替换所有选项卡。