你能解释一下,当我将typehinded父类的子类的实例传递到函数中时,PyCharm为什么会给我警告Expected type 'Type[BaseObject]', got 'LongObject' instead
吗?
我使用Python 3.9,Pycharm 2021.2.3
代码在这里:
from dataclasses import dataclass
from typing import Type
@dataclass
class BaseObject:
name: str
color: str
@dataclass
class LongObject(BaseObject):
length: int
@dataclass
class WideObject(BaseObject):
width: int
def print_object_name(obj: Type[BaseObject]):
print(obj.name)
long_thing = LongObject(name='LONG', color='RED', length=42)
print_object_name(long_thing)
wide_thing = WideObject(name='LONG', color='RED', width=88)
print_object_name(wide_thing)
此处的类型注释错误:
def print_object_name(obj: Type[BaseObject]):
print(obj.name)
要将obj
注释为BaseObject
类型的实例,只需执行以下操作:
def print_object_name(obj: BaseObject):
print(obj.name)
当对象本身是一个类型而不是该类型的实例时,使用Type
类型,例如,如果要执行以下操作:
print_object_name(LongObject)
自变量将具有Type[LongObject]
的类型,它是Type[BaseObject]
的子类型,就像LongObject
是BaseObject
的子类型一样。