Implement abstractmethod using the __getattr__ dunder method

Viewed 378

I have a class that implements an interface, but I don't want to explicitly implement some of the methods.
So I am using __getattr__ dunder method for these methods, However I receive a TypeError when I do it.

TypeError: Can't instantiate abstract class Worm with abstract methods run

Example code:

from abc import ABCMeta, abstractmethod
class AnimalInterface(metaclass=ABCMeta):
    @abstractmethod
    def eat(self, food):
        ...

    @abstractmethod
    def run(self):
        ...

class Worm(AnimalInterface):
    def eat(self, food):
        pass

    def __getattr__(self, name):
        """this for methods that there is no need to specifically implement them"""
        return lambda *a, **kw: None
Worm()
1 Answers

This is a complete violation of interface segregation (SOLID). Maybe reconsider the design of your interface to make it more client specific?

Related