栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

python 3.5类型提示:我可以检查函数参数是否匹配类型提示吗?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python 3.5类型提示:我可以检查函数参数是否匹配类型提示吗?

Python本身不提供此类功能,您可以在此处了解更多信息:


我为此写了一个装饰器。这是我的装饰器的代码:

from typing import get_type_hintsdef strict_types(function):    def type_checker(*args, **kwargs):        hints = get_type_hints(function)        all_args = kwargs.copy()        all_args.update(dict(zip(function.__pre__.co_varnames, args)))        for argument, argument_type in ((i, type(j)) for i, j in all_args.items()): if argument in hints:     if not issubclass(argument_type, hints[argument]):         raise TypeError('Type of {} is {} and not {}'.format(argument, argument_type, hints[argument]))        result = function(*args, **kwargs)        if 'return' in hints: if type(result) != hints['return']:     raise TypeError('Type of result is {} and not {}'.format(type(result), hints['return']))        return result    return type_checker

您可以这样使用它:

@strict_typesdef repeat_str(mystr: str, times: int):    return mystr * times

虽然将您的函数限制为仅接受一种类型不是很pythonic。虽然您可以使用abc(

number
或自定义abc)之类的abc(抽象基类)作为类型提示,并限制您的函数不仅接受一种类型,还可以接受所需类型的任意组合。


如果有人要使用它,请添加一个github存储库。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/659602.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号