The goal:
- B in inherits from A.
- A and B have a factory method
create
, which harmonizes different input types before initializing the actual class. create
calls different create methodscreate_general_1
,create_general_2
,create_specific_b_1
via their name, supplied as a string.
This is my current approach:
import sys
class A:
def __init__(self, text):
self.text = text
print("I got initialized: {}".format(text))
def create(create_method_str):
# This is where it breaks:
create_method = getattr(sys.modules[__name__], create_method_str)
return create_method()
def create_general_style_3():
return A("a, #3")
class B(A):
def create_b_style_1():
return B("b, #1")
if __name__ == "__main__":
B.create("create_b_style_1")
It fails with the following error:
Traceback (most recent call last): File "test.py", line 22, in B.create("create_b_style_1") File "test.py", line 10, in create create_method = getattr(sys.modules[__name__], create_method_str) AttributeError: 'module' object has no attribute 'create_b_style_1'
So in a way, I'm trying to combine three things: factory methods, inheritance, and function calling by name. It would be great if someone had a smarter approach, or knew how to get this approach to work.
Thanks a great lot!