【问题标题】:Python–Object AttributeError when accessing class attribute python访问类属性python时Python–Object AttributeError
【发布时间】:2015-08-02 22:34:07
【问题描述】:

我有三个班级: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)

【问题讨论】:

  • 执行self.attrs = ['name','image','reuseable','value'] 会为类的实例提供一个名为attrs 的属性,该属性是一个字符串列表,不是 单独的属性名为'name'、'image' 、“可重用”和“价值”。
  • 为什么在使用super 时将self 作为第一个参数传递给__init__
  • 再次阅读我上面的评论。您对super 的所有呼叫都是错误的。对所有这些都像在 BronzeSword 上所做的那样做
  • 您的Item 类需要从object(新式类)继承,否则super() 将无法正常工作
  • self 不应该是super()Weapon 内部调用中的第一个参数

标签: python object inheritance pygame subclassing


【解决方案1】:

您没有发布实际导致错误的代码 - 即您访问属性的位置。但是,您不能通过引用类来访问实例属性 - 它们存储在单独的 __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__(...):
        ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 2017-07-17
    相关资源
    最近更新 更多