BLUF: I release this may lead to an opinionated flag, but I am looking to see what experienced Python users may do in this case. I am not looking for a "What's the best design pattern?" answer.
Working on a personal project that has the following aspects:
- 1 baseclass
- 2 subclasses
- 3 possible variations of subclasses by type
The baseclass determines shared operations between all the subclasses and variations. The subclasses are determined by what file type the class will be used for (thus the methods do the same thing, but differently). The variations further determine how a subclass does work.
An example:
Both classes
AandBare varied, 'A' to supportrectobjects andBforcircleobjects. Each have a method calledinsertand because their variations are different, the methods are implemented differently.If we furthered the example, say both are varied to support
rectobjects. Each have a method calledwriteand because their file types are different, they are implemented differently.
At first I thought a factory method would be appropriate for this: provide file type and variation parameters and return a class that supports it. Then after doing some reading, I've found that perhaps simply calling the concrete classes directly would be a viable approach with less abstraction (i.e. kls = factory() vs kls = ARectFoo()).
Unlike Java or C++ where class encapsulation is protected (via private), Python is completely exposed and the "Zen" would show that both patterns would be perfectly acceptible. However, is one more pythonic than the other? Or am I missing another pattern all together that would better align to class instation sequence?
Supporting information:
# An example listing of classes
class Base:
# stuff
class A(Base): # Subclass supporting file type A
# ...
class B(Base): # Sublcass supporting file type B
# ...
class ARect(A):
# ...
class ACircle(A):
# ...
class ATriangle(A):
# ...
class BRect(B):
# ...
class BCircle(B):
# ...
class BTriangle(B):
# ...
Aucun commentaire:
Enregistrer un commentaire