我有三个课程:Item
,Weapon
和BrassSword
当我尝试访问其中一个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)
答案 0 :(得分:4)
您没有发布实际导致错误的代码 - 即您访问该属性的位置。但是,您无法通过引用类来访问实例属性 - 它们存储在单独的__dict__
中。您的超类在__init__()
中实例化时将这些属性设置为self
的属性。在此之后,只能通过self
实例访问它们。
如果您尝试以与此类似的方式访问该属性:
a = BrassSword.image
相反,你想要访问它:
sword = BrassSword()
a = sword.image
或:
sword = BrassSword().image
如果您希望在所有BrassSword实例中共享一个图像,则需要将其声明为类似这样的类属性:
class BrassSword(Weapon):
image = 'path/to/image'
def __init__(...):
...