我在 VSCode 上使用 Pylance,我得到这个变量的reportUnknownMemberType警告/错误,即使我可以看到它知道类型。
我对课程很陌生,所以如果有更好的方法可以做到这一点,请告诉我。我的目标是在子类中使用更多键来扩展父类字典。该程序实际上正在运行,父 dict 获取新的键、值对,但我想知道为什么会出现 Pylance 错误。
以下是这些类的继承链,名称简化但结构真实。涉及 3 个类,继承如 Base > SubClass > SubSubClass。Base 类位于一个单独的文件中:
#base.py
class Base:
def __init__(self, param0: str) -> None:
self.param0 = param0
self.exportable = dict[str, object]()
其他 2 个类位于第二个文件中:
# subclasses.py
class SubClass(Base):
def __init__(self, param0: str, param1: str, param2: str,
param3: str, param4: str,
param5: bool=True) -> None:
super().__init__(param0)
self.param1 = param1
self.param2 = param2
self.param3 = param3
self.param4 = param4
self.param5 = param5
self.exportable = {
self.param0: {
'param1': self.param1,
'param2': self.param2,
'param3': self.param3,
'param4': self.param4,
'param5': self.param5
}
}
class SubSubClass(SubClass):
def __init__(self, param1: str, param3: str) -> None:
super().__init__(name='hardcodedparam0', param1=param1, type='hardcodedparam2', param3=param3,
param4='hardcodedparam4')
self.properties = {
'name': {
'type': "string"
},
'contentBytes': {
'type': 'string',
'format': 'byte'
}
}
# this is where I get the error
new_exportable = self.exportable.copy()
self.exportable = {**new_exportable, **self.properties}
我最初的计划是只使用self.exportable[self.name]['properties'] = self.properties
而不是那个 dict 合并,但我得到这个不能分配错误。
我也尝试在 SubSubClass 中使用 访问 SubClass self.exportable
,super().exportable
虽然我认为没有必要,但是当我运行程序时,我得到一个错误,说super() has no attribute 'exportable'。对于它的价值,此super()
尝试在不运行程序时也会从上面给出相同的“无法分配”错误。
使用第一个选项(dict 合并)和第二个选项(分配新的属性键和值),程序可以工作并且self.properties
dict 成功地附加到继承的self.exportable
dict 上。但我想知道我是否做错了什么,或者 Pylance 是否只是感到困惑。我认为它很困惑,因为在 SubClass 中它看到 dict 只是dict[str,Union[str,bool]]
然后 SubClass B,而不是那个Union[str,bool]
值,试图添加properties
dict,它是一组 dict 本身?
当然,我可以让 Pylance 配置中的 reportUnkownMemberType 错误静音,但我担心我掩盖了一些我不知道的东西。
谢谢