【发布时间】:2017-11-03 23:02:32
【问题描述】:
我正在尝试将 Python 的 type annotations 与抽象类一起使用。
我的__init__ 函数如下所示:
from abc import ABCMeta
class SomeClass(object, metaclass=ABCMeta):
def __init__(self, *args, **kwargs):
print("Initiating %s object.", self.__class__.__name__)
self.username = kwargs['data']
assert isinstance(self.username, str)
is_premioum = kwargs.get('premioum', False)
self.money_investmant = kwargs.get('investmant')
if isinstance(self.money_investmant, str):
self.money_investmant = float(self.money_investmant)
如您所见,kwargs 可以包含来自多种类型的参数 - float、bool 和 str。
现在,我正在尝试为函数编写类型注释,如下所示:
def __init__(self, *args, **kwargs: Union[bool, str, float]) -> None:
但是我的PyCharm IDE 提醒我:
除了类型 'Integral',改为使用 'str'
还有:
在 bool | 中找不到引用“get”字符串 |浮动'
我做错了吗?
如果kwargs包含多种类型的参数,我应该如何编写类型注释?
【问题讨论】:
标签: python python-3.x type-hinting typing keyword-argument