Yaroslav Hladkyi
Yaroslav Hladkyi

Reputation: 335

Call __call__ method from both parents classes

I have classes:

class C1():
    def __call__(self,name='1'):
        self.name=name
        print(self.name)

class C2():
    def __call__(self,name='2'):
        self.name=name
        print(self.name)

class C3(C1, C2):
    def __call__(self,name='=>35'):
        super().__call__()
        self.name=name
        print(self.name)

The result:

1
=>35

But what I expect:

1
2
=>35

How to call this method from both parents classes?

Upvotes: 0

Views: 116

Answers (1)

Axe319
Axe319

Reputation: 4365

super() just gets the next in the method resolution order or "mro". It doesn't magically call multiple methods at once.

Typically you would place a super() call in each class. That way it always resolves itself. In this case the last one in line will raise an AttributeError.

However you could get around this by checking if your method has the method you are trying to call in your parent class.

class C1():
    def __call__(self,name='1'):
        self.name=name
        print(self.name)
        # I'm sure ther is a more pythonic way to do this
        # but this just checks if your super class has a
        # call method before calling it
        # you could just try catch the AttributeError as well
        # either way, your IDE will probably complain about this.
        super_class = super()
        if hasattr(super_class, '__call__'):
            super_class.__call__()

class C2():
    def __call__(self,name='2'):
        self.name=name
        print(self.name)
        super_class = super()
        if hasattr(super_class, '__call__'):
            super_class.__call__()

class C3(C1, C2):
    def __call__(self,name='=>35'):
        super().__call__()
        self.name=name
        print(self.name)

foo = C3()
foo()

Upvotes: 1

Related Questions