Implement abstract method in inheritance in Python

3

The following class hierarchy, where class "A" has an abstract method called "foo":

# -*- coding: utf-8 -*-
import abc


class A:
    __metaclass__ = abc.ABCMeta

    def __init__(self):
        pass

    @abc.abstractmethod
    def foo(self):
        return


class B(A):
    def __init__(self):
        super(B, self).__init__()
        pass 

    def foo(self):
        print 'Foo method in class B'


class C(B):
    def bar(self):
        print 'Bar method in class C'


def main():
    class_c = C()
    class_c.foo()
    class_c.bar()


if __name__ == "__main__":
    main()

This code works perfectly by printing the following:

"Foo method in class B"
"Bar method in class C"

My question is that Pycharm says that class "C" should implement all abstract methods, in this case the methods defined in class "A".

Is there a convention that says I have to implement all abstract methods? Is there a problem in not implementing?

    
asked by anonymous 01.12.2015 / 21:31

2 answers

3

You may know that this form is not very phytonica . When you want guarantees in the code, it is better to use another language. This is probably why PyCharm claims this. It does not go very far to check if everything is in order.

So he does not see the implemented method there and thinks it's a problem. It is not. The important thing is to have the method implemented. And it was in class B and obviously will be inherited by C .

    
02.12.2015 / 11:05
0

I need to disagree with the above opinion:

  

You may know that this form is not very phytonic. When you want guarantees in the code, it is better to use another language.

This is a major confusion that many Python programmers are making about language and how to implement certain codes. The fact that Python is flexible and does not force you to follow certain "standards" does not mean that you should not use them or use other languages that "force" the use of the standard, such as Java.

In the case of this post, when you use the ABC class as the metaclass of a class A, you are telling Python that all objects that inherit from this class must "necessarily" implement all methods of class A. Therefore , Pycharm is complaining.

This type of implementation is widely used when building classes that implement the "interfaces" pattern.

If you wanted more details you can see this link: Is there interfaces in python?

    
31.05.2018 / 23:23