3

I use pep8 in visual studio code and I just tried to write some abstract classes.

The problem is I get the error [pylint] E1101:Instance of 'MyAbstract' has no 'child_method' member because pep8 does not realise that the method is well defined, but in the child classes.

To illustrate my problem here is a code snippet that is reducted to the minimum for clarity:

class MyAbstract:

    def some_method(self):
        newinfo = self.child_method()
        # use newinfo 

class MyChild(MyAbstract):

    def child_method(self):
        # Do something in a way

class OtherChild(MyAbstract):

    def child_method(self):
        # Do the same thing in a different way

So my questions are:

  • Is it ok to write classes like this?
  • How would you solve the error? (disable error, use another pattern, ...)

Clarification

The MyAbstract class shouldn't be instanciated, and the child classes will inherit the some_method. The idea is to use it on child class instances.

Romain Vincent
  • 2,875
  • 2
  • 22
  • 29
  • 1
    you should define the method on the abstract class; either have it be an empty method using `pass` if you don't intend to require the child to override it, or have it throw an error if you do – Hamms Aug 04 '17 at 22:39
  • thank you for thjis suggestion, will be easier to do than to add rule deactivations everywhere! – Romain Vincent Aug 04 '17 at 22:41

1 Answers1

5

If you want MyAbstract to be an abstract class with abstract method child_method, Python has a way of expressing that in the abc module:

import abc

class MyAbstract(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def child_method(self):
        pass

    def some_method(self):
        newinfo = self.child_method()
        do_whatever_with(newinfo)

Your linter will no longer complain about the nonexistent method, and as a bonus, Python will detect attempts to instantiate a class with unimplemented abstract methods.

user2357112
  • 260,549
  • 28
  • 431
  • 505