Tôi đang thử sử dụng Python type annotations
với lớp trừu tượng. chức năng My __init__
trông như thế này:Nhập chú thích có nhiều loại trong ** 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)
Như bạn có thể thấy, có thể chứa kwargs
lập luận từ một số một số types- float
, bool
và str
.
Bây giờ, tôi đang cố gắng để viết kiểu chú thích cho hàm, trông như thế này:
def __init__(self, *args, **kwargs: Union[bool, str, float]) -> None:
Nhưng PyCharm
IDE của tôi báo cho tôi:
Trừ gõ 'Integral', có 'str' thay
Và:
Không thể tìm thấy tham chiếu 'get' trong bool | str | float '
Tôi có làm gì sai không?
Tôi nên viết chú thích loại cho kwarg nếu nó chứa đối số từ nhiều loại như thế nào?