0

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.

timakro
  • 1,739
  • 1
  • 15
  • 31
  • 1
    I'm not really sure what you're trying to do, but it sorta sounds like you want `Higher`()` to be a factory, not a `class`. `def higher1(value): if "blue" == value: return HigherBlue()` etc ...? – dwanderson Jan 07 '16 at 16:01
  • Have you researched inheritance? You can create subclasses of **Higher1** and override the **__init__** method. – abe Jan 07 '16 at 16:23
  • Possible duplicate of [Reverse mapping class attributes to classes in Python](http://stackoverflow.com/questions/1263479/reverse-mapping-class-attributes-to-classes-in-python) – timakro Jan 07 '16 at 17:51

1 Answers1

0

Using the following link I was able to achieve what I wanted:

Reverse mapping class attributes to classes in Python

I didn't want to vote for duplicate because it's not exactly the same question and it would have taken a long time to wait for 50 votes, all the time people could spend time on finding a solution when I already got one.

Community
  • 1
  • 1
timakro
  • 1,739
  • 1
  • 15
  • 31