Reputation: 50
From what I have understood so far (notice telling to me the correctness of the definition in my words): We should declare our abstract methods in the abstract class and led the implementation of those methods to the subclass or derived class.
Now I have 1 question:
Or, if not:
Should we have our instantiation in the derived class(child class) or in both?
Which one is better to do, or better to say pythonic?
Or you may say it does not matter...if that is the case notice telling me why please.
for example, this:
from abc import abstractmethod, ABC
class Athlete(ABC):
def __init__(self, name: str, mass: int, height: int, nationality: str):
self.name = name
self.mass = mass
self.height = height
self.nationality = nationality
@abstractmethod
def run(self):
pass
def play(self):
pass
def exercise(self):
pass
def sleep(self):
pass
class SoccerPlayer(Athlete):
def run(self):
print(f"{self.name} is running")
def play(self):
print(f"{self.name} with {self.height} is running to save his {self.nationality} nation.")
def exercise(self):
print(f"{self.name} is exercising to fit his {self.mass}")
def sleep(self):
print(f"{self.name} is sleeping 8 h a day to increase his {self.height}m height.")
player = SoccerPlayer('ali', 200, 180, 'american')
player.run()
Upvotes: 1
Views: 167
Reputation: 532093
For testing, it may be convenient to instantiate an abstract base class. It's also fairly simple to do. Don't do this in production code, though.
All you need to do is empty Athlete.__abstractmethods__
>>> Athlete("bob", 100, 200, "american")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Athlete with abstract methods run
>>> Athlete.__abstractmethods__
frozenset({'run'})
>>> Athlete.__abstractmethods__ = frozenset()
>>> Athlete("bob", 100, 200, "american")
<__main__.Athlete object at 0x10c9c0410>
Upvotes: 2
Reputation: 761
always do the instantiation for the derived class.
because although if you do the instantiation in the base class you will inherit those attributes and methods in the derived class, but also consider this point that, you may want to override the attributes that you have instantiated in the base class(abstract class). and in that time you would need to rapidly modify your attributes in abstract class which is not a good idea.
So instantiate your attributes in the child class not the abstract class.
Upvotes: 1