gpt4 book ai didi

用于文档的 Python 接口(interface)

转载 作者:行者123 更新时间:2023-11-30 21:54:00 25 4
gpt4 key购买 nike

据我所知,在 Python 中我们使用鸭子类型而不是实现具体的接口(interface)。

因此,如果您有一个函数接受需要能够吃喝的动物对象,您只需调用 .eat().drink() 以及传入的任何对象只需要确保以适合它们的方式包含这些方法。

调用你的函数时,没有必要创建一个每个人都实现的接口(interface)。

但是为了文档和新的 Python3 类型提示,是否有任何正确的方法来创建接口(interface)。

类似...

interface Animal:
eat()
drink()

def foo(a: Animal):
a.eat()
a.drink()

...其中接口(interface)Animal纯粹用于文档和foo函数中的非强制类型提示。它在运行时从不使用,并且将动物传递到函数中的那些仍然遵循鸭子类型协议(protocol)。

这在Python中可能吗?

最佳答案

您可以为此使用 ABC(抽象基类)。基类(读作“接口(interface)”)需要将 metaclass 设置为 abc.ABCMeta,或者从某件事中衍生出来。然后,您可以使用装饰器来指示必须重写方法。

import abc

class Animal(metaclass=abc.ABCMeta):
@abc.abstractmethod
def eat(self):
pass

@abc.abstractmethod
def drink(self):
pass

def foo(a: Animal):
a.eat()
a.drink()

属性、类方法和静态方法也可以通过使用之前之前的普通装饰器来抽象化 @abc.abstractmethod:

@property
@abc.abstractmethod
def data(self):
return self._data

@classmethod
@abc.abstractmethod
def abstract_classmethod(cls, ...):
pass

@staticmethod
@abc.abstractmethod
def abstract_staticmethod(...):
pass

这里正在使用...

In [40]: class Animal(metaclass=ABCMeta):
...: @abstractmethod
...: def eat(self):
...: print('Eats...')
...: @abstractmethod
...: def drink(self):
...: print('Drinks...')
...:
...:

In [41]: def foo(a: Animal):
...: a.eat()
...:

In [42]: class Elephant:
...: def eat(self):
...: print('Elephant eating...')
...: def drink(self):
...: print('Elephant drinking...')
...:


In [43]: class Giraffe(Animal):
...: def eat(self):
...: print('Giraffe eats...')
...: def drink(self):
...: print('Giraffe drinks...')
...:

In [44]: giraffe = Giraffe()

In [45]: elephant = Elephant()

In [46]: isinstance(giraffe, Animal)
Out[46]: True

In [47]: isinstance(elephant, Animal)
Out[47]: False

In [48]: foo
Out[48]: <function __main__.foo(a: __main__.Animal)>

In [49]: foo(giraffe)
Giraffe eats...

In [50]: foo(elephant)
Elephant eating...

In [51]: foo(Animal())
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-51-e060be6dff03> in <module>
----> 1 foo(Animal())

TypeError: Can't instantiate abstract class Animal with abstract methods drink, eat

关于用于文档的 Python 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59440417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com