Python中如何正确重写带省略号默认参数的方法?(PySide6场景)
解决QStandardItem子类化时Pylance类型错误的方法
问题根源:PySide6的类型存根文件中用
...作为默认参数占位符,但实际QStandardItem.data()的默认role参数是Qt.DisplayRole(类型为int)。Pylance会严格校验类型匹配,直接用...作为子类方法的默认参数会触发类型不匹配错误。推荐解决方案:使用实际默认枚举值
导入QtCore.Qt,将默认参数指定为Qt.DisplayRole,既符合类型标注要求,又与父类行为完全一致:from typing import Any from PySide6.QtGui import QStandardItem from PySide6.QtCore import Qt class A(QStandardItem): def data(self, role: int = Qt.DisplayRole) -> Any: return super().data(role)备选妥协方案:临时忽略类型检查
如果暂时不想硬编码默认值,可以添加# type: ignore注释抑制Pylance错误,但不推荐长期使用:from typing import Any from PySide6.QtGui import QStandardItem class A(QStandardItem): def data(self, role: int = ...) -> Any: # type: ignore return super().data(role)
内容的提问来源于stack exchange,提问作者usan
相关产品推荐
相关产品推荐

