python - 类型提示。如何暗示传递给函数的对象必须具有某种方法/属性访问权限?
问题描述
请看一个使用 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 文档字符串来指定此类类型提示?
解决方案
定义一个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
推荐阅读
- django-rest-framework - 发布数据时 Django REST API 中的 HTTP 400 错误请求
- python - 使用词干清理数据后如何获取单词列表
- javascript - 如何在javascript中的另一个文件中更改文件中的值变量
- java - 映射列表的最佳做法是什么
没有堆栈溢出 - .net-core - 无法使用 .NET Core 反序列化 JSON 字符串
- python - html页面末尾的空白是什么引起的?
- javascript - 提交按钮未重新启用
- reactjs - 将 non-create-react-app React 项目部署到 Github Pages 时出现问题
- python - 搜索中的 Visual Studio Code 键绑定
- javascript - 我如何从输入值文本中获取?