Reputation: 543
I have to model several cases, each case is realised by a class
. I want to make sure that each class
must have 2 methods get_input()
and run()
. So in my opinion, I can write a CaseBase
class where these 2 methods are decorated as @abstractmethod
. Therefore, any child class has to implement these 2 methods. And this is exactly my goal.
However, due to the nature of my work, each case is for distinct subject, and it is not easy to define a fixed group of attributes. The attributes should be defined in the __init__
method of a class
. That means I don't know what exactly attributes to write in the CaseBase
class. All I know is that all children cases must have some common attributes, like self._common_1
and self._common_2
.
Therefore, my idea is that I also decorate the __init__
method of CaseBase
class by @abstractmethod
. See my code below.
from abc import ABC, abstractmethod
from typing import Dict, List
class CaseBase(ABC):
@abstractmethod
def __init__(self):
self._common_1: Dict[str, float] = {}
self._common_2: List[float] = []
...
@abstractmethod
def get_input(self, input_data: dict):
...
@abstractmethod
def run(self):
...
class CaseA(CaseBase):
def __init__(self):
self._common_1: Dict[str, float] = {}
self._common_2: List[float] = []
self._a1: int = 0
self._a2: str = ''
def get_input(self, input_data: dict):
self._common_1 = input_data['common_1']
self._common_2 = input_data['common_2']
self._a1 = input_data['a1']
self._a2 = input_data['a2']
def run(self):
print(self._common_1)
print(self._common_2)
print(self._a1)
print(self._a2)
def main():
case_a = CaseA()
case_a.get_input(input_data={'common_1': {'c1': 1.1}, 'common_2': [1.1, 2.2], 'a1': 2, 'a2': 'good'})
case_a.run()
if __name__ == '__main__':
main()
My question: Is my way a good Python style?
I followed many Python tutorials about how to make Abstract class and child class. They all give examples where a fixed group of attributes are defined in the __init__
method of the base class. I also see some approach to use super().__init__
code in the child class to change the attributes defined in the base class or to add new attributes. But I am not sure if it is better (more pro) than my way.
Thanks.
Upvotes: 0
Views: 668
Reputation: 1755
You mostly used the abc
module in python 3.10 correctly. but it doesn't make sense to decorate the constructor with @abstractmethod
. It's unnecessary. Each class, derived or not, can and will have its own constructor. You can call super().__init__(args)
within the child class to call the constructor of its immediate parent if you didn't want to duplicate its code but wanted to do further initialization in the child class constructor.
Upvotes: 1