首页 > 解决方案 > 类型提示。如何暗示传递给函数的对象必须具有某种方法/属性访问权限?

问题描述

请看一个使用 numpy doctstring 进行类型提示的示例:

def my_function(obj):
    """Do some work.

    Parameters
    ----------
        obj : Any class with `do_work()` method
    Returns
    -------
    None
    """
    time.sleep(5)

我想知道是否有办法告诉调用者函数需要具有do_work方法的对象?有没有办法使用python3/mypy 类型提示或/和 numpy 文档字符串来指定此类类型提示?

标签: pythonpython-2.7type-hinting

解决方案


定义一个Protocol

import typing


class Worker(typing.Protocol):
    def do_work(self):
        pass


class SomeWorker:
    def do_work(self):
        print("Working...")


def my_function(obj: Worker):
    obj.do_work()


x = SomeWorker()
my_function(x)  # This will type check; `SomeWorker` doesn't have to inherit from Worker

推荐阅读