1

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

oopsNoobs
  • 21
  • 4
  • Does this answer your question? [Abstract attribute (not property)?](https://stackoverflow.com/questions/23831510/abstract-attribute-not-property) – jfaccioni Mar 28 '22 at 11:50

1 Answers1

0

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
rhurwitz
  • 2,557
  • 2
  • 10
  • 18