Python--访问class属性时对象属性错误python

Python–Object AttributeError when accessing class attribute python

我有三个 类:ItemWeaponBrassSword 当我尝试访问 BrassSword 的属性之一时(名称、图像等)它说,AttributeError: class BrassSword has no attribute 'image'

代码如下:

import pygame, math, random

class Item(object):
    def __init__(self,name,image,reuseable,value):
        self.image=pygame.image.load(image)
        self.itemattrs = ['name','image','reuseable','value']
        self.path = image
        self.name = name
        self.x=0
        self.y=0
        self.reusable = reuseable
        self.value = value
        self.rect = [self.x,self.y,self.image.get_size()[0],self.image.get_size()[1]]
    def onUse(self):
        pass
    def onThrow(self):
        pass

class Weapon(Item):
    def __init__(self,name,image,value,damage,maxdamage,speed):
        super(Weapon,self).__init__('Weapon',image,True,value)
        self.itemattrs = ['name','image','damage','maxdamage','value','speed']
        self.damage=damage
        self.maxdamage=maxdamage
        self.speed = speed # Cooldown in frames
        self.cooldown = 0
    def onUpdate(self):
        self.cooldown -= 1
    def onUse(self,targetEntity):
        if self.cooldown > 0:
            return
        self.cooldown = speed
        targetEntity.hp-=random.range(damage,maxdamage)

        if targetEntity.hp <= 0:
            targetEntity.onDie()
    def onThrow(self):
        pass # TODO: Add throwing weapons

class BrassSword(Weapon):
    def __init__(self):
        super(BrassSword,self).__init__('item.weapon.brass_sword','testlevel/Ball.png',True,value,3,10,12)

您没有 post 实际导致错误的代码 - 即您访问属性的位置。但是,您无法通过引用 class 来访问实例属性 - 它们存储在单独的 __dict__ 中。您的 superclass 在 __init__() 中实例化时将这些属性设置为 self 的 属性。此后,它们只能通过 self 实例访问。

如果您尝试访问与此类似的属性:

a = BrassSword.image

相反,您想像这样访问它:

sword = BrassSword()
a = sword.image

或:

sword = BrassSword().image

如果您想在所有 BrassSword 实例之间共享一个图像,您需要将其声明为 class 属性,如下所示:

class BrassSword(Weapon):
    image = 'path/to/image'
    def __init__(...):
        ...