[英]Implement abstractmethod using the __getattr__ dunder method
I have a class that implements an interface, but I don't want to explicitly implement some of the methods.我有一个实现接口的 class,但我不想显式实现某些方法。
So I am using __getattr__
dunder method for these methods, However I receive a TypeError
when I do it.所以我对这些方法使用__getattr__
dunder 方法,但是当我这样做时我收到一个TypeError
。
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()
This is a complete violation of interface segregation (SOLID).这完全违反了界面隔离 (SOLID)。 Maybe reconsider the design of your interface to make it more client specific?也许重新考虑您的界面设计以使其更加针对客户?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.