马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import pygame
import numpy as np
from settings import Settings
class Star(pygame.sprite.Sprite):
def __init__(self, mass=0, radius=0, pos=(0, 0), color=(0, 0, 0), speed=(0, 0)):
self.mass = mass
self.radius = radius
self.image = pygame.Surface((radius * 2, radius * 2)).convert_alpha()
self.image.fill((0, 0, 0, 0))
pygame.draw.circle(self.image, color, (radius, radius), radius)
self.rect = self.image.get_rect()
self.rect.center = pos
self.settings = self.settings
self.trail = []
self.speed = np.array(speed)
def dist_to(self, other: Star):
dx = self.rect.x - other.rect.x
dy = self.rect.y - other.rect.y
d = (dx ** 2 + dy ** 2) ** 0.5
return d
信息如下:PS E:\Python\a> & D:/Python/python.exe e:/Python/a/sprite.py
pygame 2.3.0 (SDL 2.24.2, Python 3.9.9)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "e:\Python\a\sprite.py", line 5, in <module>
class Star(pygame.sprite.Sprite):
File "e:\Python\a\sprite.py", line 18, in Star
def dist_to(self, other: Star):
NameError: name 'Star' is not defined
这个报错是由于在定义`Star`类方法`dist_to`的参数类型时,使用了尚未完全定义的`Star`类。在Python中,类在其定义完成之前不可用。解决此问题的一种方法是使用字符串`'Star'`而不是直接使用`Star`来作为类型注解。
请修改`dist_to`方法的定义如下:
def dist_to(self, other: 'Star'):
dx = self.rect.x - other.rect.x
dy = self.rect.y - other.rect.y
d = (dx ** 2 + dy ** 2) ** 0.5
return d
这将消除报错,并允许您的代码正常运行。使用字符串作为类型注解在Python中是一种常见的做法,尤其是在涉及到相互引用或尚未定义的类时。
|