Search code examples
pythonabstract-class

how to create __add__ function for two abstract classes


Say I have an abstract class as such:

class Something:
 
    def __init__(self, some):
        self.some = some

    @property
    def thing(self):
        thing_obj = self.build()
        assert (thing_obj, some_addable_obj)
        return thing_obj

    @abstractmethod
    def build(self):
        raise NotImplementedError()

I am looking to create something that will __add__ subclasses, i.e.

class OneThing(Something):
    def __init__(self):
        super().__init__(some=None)
    def build(self):
        return some_addable_obj

class TwoThing(Something):
    def __init__(self):
        super().__init__(some=0)
    def build(self):
        return some_addable_obj

Now, within Something, I'd like to define and __add__ function such that:

def __add__(self, other):
    sm = Something(some=self.some)
    sm.thing = self.thing + other.thing
    return sm

However, I am getting an error in a more complex version of simplification above:

TypeError: Can't instantiate abstract class Something with abstract methods build

Any ideas on how to do this?


Solution

  • When you mark the build function as abstract, you are saying "don't let anyone make a concrete instance of this class, they MUST subclass and implement build".

    Depending on what exactly you are trying to do, you can either make Something a concrete class that doesn't implement build (just remove the decorator), or you must choose a concrete class (OneThing or TwoThing) to return from an add.