2

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")
asked Mar 28, 2022 at 5:35

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

Hey, Thanks for your code. i added some more code, can you please review it? :)
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.
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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.