具有不同参数的Python中的继承

问题描述 投票:2回答:2

当子类继承自超类时,子类是否必须具有超类所具有的所有参数?例如:“车辆(颜色,车轮,尺寸)”是超类。除了“size”属性/参数之外,我是否可以拥有一个继承Vehicle的所有子类?

This is the parent class:

class LagStudent:

    def __init__(self, name, dept, cgpa, is_a_scholar):
        self.name = name
        self.dept = dept
        self.cgpa = cgpa
        self.is_a_scholar = is_a_scholar

Below are two subclasses:

class CovStudent(LagStudent):

    def __init__(self, name, dept, cgpa, is_a_scholar, honours):
        super().__init__(name, dept, cgpa, is_a_scholar)
        self.honours = honours


class OxStudent(CovStudent):

    def __init__(self, name, dept, cgpa, is_a_scholar):
        super().__init__(name, dept, cgpa, is_a_scholar) 

When I run the following...

student4 = OxStudent("Mark", "Mathematics", 4.62, True)
print(student4.is_a_scholar)

It gives Error:

TypeError:init()缺少1个必需的位置参数:'honors'

python python-3.x inheritance
2个回答
2
投票

我们将Vehicle超类定义如下,并将Bicycle子类定义如下

class Vehicle:

    def __init__(self, colour, wheels, size):

        self.colour = colour
        self.wheels = wheels
        self.size = size

class Cycle(Vehicle):

    def __init__(self, colour, wheels, size):

        super().__init__(colour, wheels, 'small')

在这里你可以看到Cycle子类只接受colorswheels并将它传递给超类,并具有硬编码的size=small属性。子类构造函数调用超类的构造函数

要检查发生了什么,我们可以尝试如下:

veh = Cycle('Black', 2)
print(veh.colour)
print(veh.wheels)
print(veh.size)
#Black
#2
#small

更新根据OP不想要大小属性的注释,您可以为超类中的size属性指定一个默认值,例如: size=None,你不需要在实例化子类时传递它。

class Vehicle:

    def __init__(self, colour, wheels, size=None):

        self.colour = colour
        self.wheels = wheels
        self.size = size

class Cycle(Vehicle):

    def __init__(self, colour, wheels):

        super().__init__(colour, wheels)

然后您可以按如下方式调用此方法

veh = Cycle('Black', 2)
print(veh.colour)
print(veh.wheels)
print(veh.size)
#Black
#2
#None

您可以看到size的值是None,这是我们选择的默认值,因为我们没有明确地传递size,如果我们已经通过它,我们将获得size属性的值


0
投票

子类当然可以从__init__方法的超类中获得不同的签名。它只需要调用其超类的__init__方法与该方法所期望的:

class Vehicle:
    def __init__(self, colour, wheels, size):
        self.colour = colour
        self.wheels = wheels
        self.size = size

class Car(Vehicle):
    def __init__(self, colour, wheels):
        super().__init__(colour, wheels, 'small')

print(Car('white', 4).size)

这输出:

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