scmg
scmg

Reputation: 1894

python - non-abstract method calls abstract methods

I have an example below:

The first script where I define the abstract class:

# test.py

from abc import ABCMeta, abstractmethod


class A:
    __metaclass__ = ABCMeta

    def __init__(self, a):
        self.x = a
        self.y = 0

    @abstractmethod
    def __foo_1(self):
        pass

    @abstractmethod
    def __foo_2(self):
        pass

    # that is what i'm wondering if it could be possible
    def run(self):
        self.__foo_1()
        self.__foo_2()

And the second script where I implement the abstract methods:

# test2.py

from test import A


class B(A):
    def __foo_1(self):
        self.y += 1

    def __foo_2(self):
        self.y += 2

Since i know for sure that __foo_1 and __foo_2 must be called in that order, i want to write the non-abstract method run to do that (like in test.py). But it doesn't seem to work:

b = B(1)
b.run()

>> TypeError: Can't instantiate abstract class B with abstract methods _A__foo_1, _A__foo_2

Is there anyway to do that? Since i don't want to rewrite the same run-method each time.

Thank you.

Upvotes: 2

Views: 414

Answers (2)

user2201041
user2201041

Reputation:

The problem is that double_underscore attributes are somewhat magic in Python.

From the docs:

Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped.

So instead of overriding __foo_1, you end up with an abstract _A__foo_1() and an implemented _B__foo_1()

Upvotes: 1

scmg
scmg

Reputation: 1894

Ok ... i found what i need, i just need to change the protected methods __foo to normal method foo and it all works.

Upvotes: 0

Related Questions