首页 > 解决方案 > 如何定义类型提示以告诉函数期望python中的类型

问题描述

为了记录我的项目/保持代码整洁,我想为我的所有函数提供一个类型提示(我对整个打字概念还是很陌生)。

我想告诉一个函数期待一个数据类型,比如 str、bool、int、dict 等。也就是你通过调用得到的type(a_var)

我意识到存在属性设置器,但是对于我的用例来说编写一个设置器是不可行的

class TypeValidator:
    def __init__(self,
                 type: **the crux of the problem**
                 ):
        self.type = type

    def validate(self, value):
        return isinstance(value, self.value)

编辑:重读了我自己的问题,我想我想问的是如何在打字时描述这个:

>>> type(type)
<class 'type'>
>>>

edit2:TypeVar是我正在寻找的,感谢Patrick Haugh

标签: pythontype-hinting

解决方案


推荐阅读