I have been learning OOPS in python and finding it a bit different from that of Java. In the below code I have written an abstract class and implemented it. Is it the right way to define the attributes of an abstract class?
class Vehicle(ABC):
@property
@abstractmethod
def color(self):
pass
@property
@abstractmethod
def regNum(self):
pass
class Car(Vehicle):
def __init__(self,color,regNum):
self.color = color
self.regNum = regNum
Is this a better way to do this?
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
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","EX9890")
1 Answer 1
If you want to define abstract properties in an abstract base class, you can't have attributes with the same names as those properties, and you need to define concrete implementations of the properties in the concrete child class:
from abc import ABC, abstractmethod
class Vehicle(ABC):
@property
@abstractmethod
def color(self):
pass
@property
@abstractmethod
def regNum(self):
pass
class Car(Vehicle):
def __init__(self, color, regNum):
self._color = color
self._regNum = regNum
@property
def color(self):
return self._color
@property
def regNum(self):
return self._regNum
c = Car("foo", "bar") # works fine; would not work if abstract methods weren't implemented
answered Mar 28, 2022 at 5:42
Samwise
72.1k3 gold badges36 silver badges52 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
oopsNoobs
Hey, Thanks for your code. i added some more code, can you please review it? :)
Samwise
The "better way" here is not to define the
Vehicle class, or to make Vehicle non-abstract and remove Car. You're not doing anything that benefits from inheritance, much less abstract inheritance.matanox
Kind of shows you how unsuited python is for object oriented programming, because every other simple OO feature will be one from of an oddball strap-on. Try to avoid the temptation to go OO in your python projects.
lang-py