Python中@overload实现setSize重载触发NotImplementedError问题求助
问题原因及解决方法
错误原因
你对@overload的用法完全搞错了。Python里的@overload只是给类型检查工具(比如mypy)提供的类型提示,带@overload的函数不能写实际执行逻辑,而且必须在所有重载签名后面,跟一个不带@overload装饰的真实实现函数——这个函数要能处理所有重载声明的参数场景。你现在两个函数都加了@overload,没有真正可执行的实现,调用自然会报错。
修正后的代码
from typing import overload, Union class YourClass: def __init__(self): self.options = [] # 重载签名1:传入tuple参数 @overload def setSize(self, size: tuple[Union[int, str], Union[int, str]]) -> None: ... # 仅保留类型提示,函数体用...占位 # 重载签名2:传入两个独立参数 @overload def setSize(self, width: Union[int, str], height: Union[int, str]) -> None: ... # 仅保留类型提示 # 实际执行的核心实现函数,不带@overload装饰 def setSize(self, size_or_width: Union[tuple[Union[int, str], Union[int, str]], Union[int, str]], height: Union[int, str, None] = None) -> None: ''' Set image size (width,height) ''' if height is not None: # 处理传入两个独立参数的情况 self.options.append(f"width=\"{str(size_or_width)}\" height=\"{str(height)}\"") else: # 处理传入tuple的情况 size = size_or_width try: self.options.append(f"width=\"{str(size[0])}\" height=\"{str(size[1])}\"") except IndexError: print("Error reading the size, aborting")
调用验证
现在不管是var.setSize((500,500))还是var.setSize(500,500)都能正常执行,类型检查工具也能正确识别参数类型。
内容的提问来源于stack exchange,提问作者user19926715
相关产品推荐
相关产品推荐

