出现名称错误:未定义名称“ IMGS”,以为我已在类中定义了它

时间:2020-04-15 07:31:26

标签: python python-3.x nameerror

在bird类中,定义了变量IMGS,但我收到Name错误,应该将其声明为全局变量。

**BIRD_IMGS** = [pygame.transform.scale2x(pygame.image.load(os.path.join("imgs", "bird1.png"))), pygame.transform.scale2x(pygame.image.load(os.path.join("imgs", "bird2.png"))), pygame.transform.scale2x(pygame.image.load(os.path.join("imgs", "bird3.png")))]

class Bird:
    **IMGS** = BIRD_IMGS
    MAX_ROTATION = 25
    ROT_VEL = 20
    ANIMATION_TIME = 5

    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.tilt = 0
        self.tick_count = 0
        self.vel = 0
        self.height = self.y
        self.img_count = 0
        self.img = self.IMGS[0]

    def draw (self, win):
        self.img_count += 1

NameError:未定义名称“ IMGS”

    # to make the wing flapping animation
        if self.img_count < self.ANIMATION_TIME:
            self.img = IMGS[0]
        elif self.img_count < self.ANIMATION_TIME*2:
            self.img = IMGS[1]
        elif self.img_count < self.ANIMATION_TIME*3:
            self.img = IMGS[2]
        elif self.img_count < self.ANIMATION_TIME*4:
            self.img = IMGS[1]
        elif self.img_count < self.ANIMATION_TIME*4 + 1:
            self.img = IMGS[0]

main()

1 个答案:

答案 0 :(得分:2)

class块的顶级定义的名称成为类属性(该类的所有实例共享的“类”对象的属性)-它们不会显示在“全局”模块名称空间中。 IOW,您必须遍历该类或其实例才能访问它们,即:

print(Bird.IMGS)
b = Bird()
print(b.IMGS)
print(b.IMGS is Bird.IMGS)

并且由于Python没有隐式的this指针,因此在您的方法中,您必须使用当前实例(self)来访问此属性:

if self.img_count < self.ANIMATION_TIME:
    self.img = self.IMGS[0]