Reputation: 169
When a subclass inherits from a superclass, must the subclass have all the arguments that the superclass has? E.g.: "Vehicle(colour, wheels, size)" is the superclass. Can I have a subclass that inherits everything from Vehicle except the "size" attribute/argument?
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
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)
student4 = OxStudent("Mark", "Mathematics", 4.62, True)
print(student4.is_a_scholar)
TypeError: init() missing 1 required positional argument: 'honours'
Upvotes: 4
Views: 5006
Reputation: 20500
We define the Vehicle superclass as follows, and Bicycle subclass as follows
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')
Here you can see that the Cycle subclass just takes in colors
and wheels
and passes it onto the superclass, and has a hardcoded size=small
attribute. The subclass constructor calls the constructor of the superclass
To check what's going on, we can try as follows:
veh = Cycle('Black', 2)
print(veh.colour)
print(veh.wheels)
print(veh.size)
#Black
#2
#small
Update
Based on OP's comment of not wanting to have a size attribute, you can assign a default value to the size attribute in the superclass, e.g. size=None
and you won't need to pass it while instantiating the subclass.
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)
You can then call this as follows
veh = Cycle('Black', 2)
print(veh.colour)
print(veh.wheels)
print(veh.size)
#Black
#2
#None
You can see that the value of size
is None
, which is the default value we picked since we did not pass size
explicitly, if we would have passed it, we would have got a value for the size
attribute
Upvotes: 5
Reputation: 107095
A subclass certainly can have a different signature for the __init__
method from its superclass. It just needs to call the __init__
method of its superclass with what that method expects:
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)
This outputs:
small
Upvotes: 1