from abc import ABC, abstractmethod
class MyABC(ABC):
@abstractmethod
def fly(self):
pass
@abstractmethod
def eat(self):
pass
@abstractmethod
def dance(self):
pass
@classmethod
def __subclasshook__(cls, C):
if any("fly" in B.__dict__ for B in C.__mro__):
# add checks for dance and eat...
return True
return NotImplemented
The subclasshook adds some duck typing DNA to the whole goose typing proposition. You can have formal interface definitions with ABCs, you can make isinstance checks everywhere, and still have a completely unrelated class play along just because it implements a certain method (or because it does whatever it takes to convince a subclasshook to vouch for it). Of course, this only works for ABCs that do pro‐ vide a subclasshook.
你的例子听起来像一个abstract class。您可以定义抽象类,并为该参数添加类型注释或显式检查其类型:
对于你的方法:
这是因为在将
param
传递给test
方法时,它必须继承MyABC
,并且为了继承MyABC
,类必须定义三个方法fly
、eat
、dance
,否则,在尝试实例化它时会引发TypeError
。你知道吗编辑:
如果希望子类不直接继承,但仍“算作”一个} :
MyABC
子类,可以使用^{现在,每个实现
fly
方法的类(或继承实现它的类)都将True
返回到以下条件:isinstance(CLASS, MyABC)
来自流畅的Python:
相关问题 更多 >
编程相关推荐