Correct way to define attributes for abstract class in Python

Viewed 538

What is the correct way to have attributes in an abstract class

from abc import ABC, abstractmethod

class Vehicle(ABC):
    
    def __init__(self,color,regNum):
        self.color = color
        self.regNum = regNum

class Car(Vehicle):

    def __init__(self,color,regNum):
        self.color = color
        self.regNum = regNum

car = Car("Red","ex8989")
print(car.color)

I went thro several codes but none of them felt as elegant as what we have in Java

1 Answers

Is your intent to delegate all attribute definition and initialization to the abstract base class? If so, you can refrain from overloading __init__ in the derived class and let the base class handle it. In Python abstract base classes are not "pure" in the sense that they can have default implementations like regular base classes.

from abc import ABC, abstractmethod

class Vehicle(ABC):
    
    def __init__(self,color,regNum):
        self.color = color
        self.regNum = regNum

class Car(Vehicle):
    pass

car = Car("Red","ex8989")
print(car.color)
Red
Related