5
我正在尝试使用Python的type annotations
和抽象类。 我__init__
功能如下:在kwargs中键入多种类型的注释
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提醒我:
除了类型“积分”,得到了'STR',而不是
和:
在bool中找不到'get' str |浮动'
我做错了什么?
如何为kwargs编写类型注释,如果它包含来自多个类型的参数?