Am I violating the template design pattern in Python?
So I have a base class where I created the template method and I wanted to create two additional classes that I can use to do a normal function return and generator function yield?
I had to override the do_something method and change the statement from "return" to keyword "yield" or is there another alternative design code changes that I should have done?
from abc import ABC, abstractmethod
class BaseClass(ABC):
def do_something(self):
x = self.do_step1()
y = self.do_step2()
return x + y
@abstractmethod
def do_step1(self):
pass
@abstractmethod
def do_step2(self):
pass
class ReturnClass(BaseClass):
def do_something(self):
x = self.do_step1()
y = self.do_step2()
return x + y
def do_step1(self):
return 1
def do_step2(self):
return 1
class YieldClass(BaseClass):
def do_something(self):
x = self.do_step1()
y = self.do_step2()
yield x + y
def do_step1(self):
return 2
def do_step2(self):
return 2
class ConcreteReturnClass(ReturnClass):
def do_step1(self):
return 3
def do_step2(self):
return 3
class ConcreteYieldClass(YieldClass):
def do_step1(self):
return 4
def do_step2(self):
return 4
if __name__ == '__main__':
return_class = ConcreteReturnClass();
print(return_class.do_something())
yield_class = ConcreteYieldClass();
print(next(yield_class.do_something()))
My goal is to create a base class to serve as a template but I wanted to reuse the same class and change the implementation from returning just a single keyword to yielding just like how generator functions are. I think I am violating the principle but I could not figure out a viable alternative.
Aucun commentaire:
Enregistrer un commentaire