Threebody1 发表于 2023-4-28 14:30:43

以下代码为何报错

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

isdkz 发表于 2023-4-28 14:34:19

这个报错是由于在定义`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中是一种常见的做法,尤其是在涉及到相互引用或尚未定义的类时。

Threebody1 发表于 2023-4-28 15:08:50

isdkz 发表于 2023-4-28 14:34
这个报错是由于在定义`Star`类方法`dist_to`的参数类型时,使用了尚未完全定义的`Star`类。在Python中,类 ...

你可以用twilight6的markdown<>bbcode来转换

isdkz 发表于 2023-4-28 15:12:22

Threebody1 发表于 2023-4-28 15:08
你可以用twilight6的markdownbbcode来转换

我有更方便的,你不觉得我回复快了很多了吗?{:10_256:}

Threebody1 发表于 2023-4-28 15:17:02

isdkz 发表于 2023-4-28 15:12
我有更方便的,你不觉得我回复快了很多了吗?

``会影响视觉效果

isdkz 发表于 2023-4-28 15:18:22

Threebody1 发表于 2023-4-28 15:17
``会影响视觉效果

好吧{:10_277:},我再改改我的脚本
页: [1]
查看完整版本: 以下代码为何报错