I have two classes, Lower
and Higher1
. When I call the parse
method of an instance of Lower
it checks which kind of higher class it represents, in my example I only show Higher1
. Then it creates an instance of this higher class and returns it. I can convert an instance of an higher class back to an instance of Lower
by calling it's build
method.
class Lower:
def __init__(self, data):
self.data = data
def parse(self):
if self.data[0] == "a":
value = self.data[1:]
return Higher(value)
else:
...
class Higher1:
def __init__(self, value):
self.value = value
def build(self):
return Lower("a" + self.value)
So far so good, now I want to create classes for every possible value of the value
attribute of Higher1
. Assuming "green"
and "blue"
are possible values there were two additionally classes called something like Higher1Green
and Higher1Blue
.
Higher1("blue")
would evaluate to an instance of Higher1Blue
.
Higher1("blue").build()
would evaluate to an instance of Lower
with the attribute data
beeing "ablue"
.
My question is if this is possible by only specifying the mapping between for example blue
and Higher1Blue
one time and not at multiple locations in the code. I don't care if the classes Higher1Blue
and Higher1Green
are generated dynamically or defined using class
.
My first approach was to overwrite the __new__
method of Higher1
to be able to return instances of Higher1Blue
or Higher1Green
instead. But I couldn't find a way to do the backwards mapping (Higher1Blue.build()
) without specifying the mapping another time.