pythonabstract-classabstract-methods

Prevent the child class of an abstract class from creating new methods


Is it possible to force a child class to have all the methods of the abstract class?

I have the following example:

class MovementsService(ABC):

  @abstractmethod
  def run():
    pass

and the child class:

class People(MovementsService):

  def run():
    print("im running")

  def move():
    print("im moving")

but I wouldn't want the child class "People" to have the possibility to implement functions that it doesn't have in the abstract class. Is this possible?

I don't know if this is a good practice either, so I am open to hear opposing opinions.

but in my case it would make sense to block the ability to create new functions because I am using the abstract class as an "interface" to one of my project's dependencies...


Solution

  • You can use __init_subclass__ to detect unexpected attributes in a subclass (at least, those appearing in the class's __dict__ attribute). I'm not really sure why this would be necessary, though.

    class MovementsService(ABC):
    
      @abstractmethod
      def run():
        pass
    
      def __init_subclass__(cls, **kwargs):
          super().__init__(**kwargs)
          for attr in cls.__dict__:
              if attr != "run":
                  raise AttributeError(f"Attribute '{attr}' not allowed")
    

    You can refine the check to only disallow callable attributes, only attributes of type function (allowing class methods and static methods), etc.