python3.7中的Duck输入实践

2024-05-17 01:26:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Python编写了一个库,我希望代码能够自我解释,但是我发现使用duck类型很困难。你知道吗

假设我有一个接受参数a的类。 该参数必须实现飞行、进食和舞蹈方法。 如果不读取整个类的代码或助手函数的代码,那么其他程序员甚至我自己怎么能容易地知道参数必须实现什么行为呢?你知道吗

在这些日子里,我在每个类上面定义了一个接口,其中包含一个自解释代码的expacated bahvior。你知道吗

有什么想法吗?更好的汤?你知道吗


Tags: 方法函数代码类型参数定义助手程序员
1条回答
网友
1楼 · 发布于 2024-05-17 01:26:24

你的例子听起来像一个abstract class。您可以定义抽象类,并为该参数添加类型注释或显式检查其类型:

from abc import ABC, abstractmethod

class MyABC(ABC):
    @abstractmethod
    def fly(self):
        pass

    @abstractmethod
    def eat(self):
        pass

    @abstractmethod
    def dance(self):
        pass

对于你的方法:

def test(param: MyABC):
    if not isinstance(param, MyABC):
        raise Exception("param must inherit MyABC.")

这是因为在将param传递给test方法时,它必须继承MyABC,并且为了继承MyABC,类必须定义三个方法flyeatdance,否则,在尝试实例化它时会引发TypeError。你知道吗

编辑:

如果希望子类不直接继承,但仍“算作”一个MyABC子类,可以使用^{}

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

现在,每个实现fly方法的类(或继承实现它的类)都将True返回到以下条件: isinstance(CLASS, MyABC)

来自流畅的Python

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.

相关问题 更多 >