Python Pygame类方法类型提示引用下游类的问题解决
解决Pygame中类定义顺序导致的类型提示未解析问题
当Mob类定义在Mobs之后时,在Mobs的方法里直接用Mob作为类型提示会触发“Unresolved reference”错误,以下三种方法可以解决:
字符串包裹类名(兼容Python 3.7及更早版本)
将类型提示里的Mob用单引号或双引号包裹,Python会将其视为字符串延迟解析:def render_image(self, sprite: 'Mob') -> tuple[Surface, Rect]: # 方法实现导入
annotations未来特性(Python 3.7+推荐)
在文件顶部导入from __future__ import annotations,此时所有类型提示都会被当作字符串处理,无需提前定义类:from __future__ import annotations import pygame from pygame import Surface, Rect class Mobs(pygame.sprite.Group): def render_image(self, sprite: Mob) -> tuple[Surface, Rect]: # 方法实现 class Mob(pygame.sprite.Sprite): # 类定义前向声明类
在Mobs定义前先声明Mob类的空占位,后续再给出实际定义(占位类会被后面的真实定义覆盖):import pygame from pygame import Surface, Rect # 前向声明占位 class Mob: pass class Mobs(pygame.sprite.Group): def render_image(self, sprite: Mob) -> tuple[Surface, Rect]: # 方法实现 # 实际的Mob类定义 class Mob(pygame.sprite.Sprite): # 类定义
内容的提问来源于stack exchange,提问作者Math chiller
相关产品推荐
相关产品推荐

