【问题标题】:Why does this code keep returning a 'has no attribute' error?为什么此代码不断返回“没有属性”错误?
【发布时间】:2013-12-22 23:54:13
【问题描述】:

我的代码如下,其中sdl2ext.Entity是第三方类。

class Grid(sdl2ext.Entity):
    def __init__(self, world):
        self.w = 3
        self.h = 3
        super(Grid,self).__init__()

    def dump(self):
        print(self.w)

def run():
    world = sdl2ext.World()
    g = Grid(world)
    g.dump()

if __name__ == "__main__":
    run()

我得到的具体错误是print(self.w):

AttributeError: object ''Grid'' has no attribute ''w''

这是否与未初始化底层基础对象 sdl2ext.Entity 有关?

【问题讨论】:

  • 设置私有属性后为什么还要初始化超类?
  • 因为这里给出的答案:stackoverflow.com/questions/10670020/…。特别是在接受的答案中给出的CastSpell 类的定义。
  • 你误会了。为什么要在设置私有属性之后而不是之前初始化超类
  • @BartoszKP 你能详细说明一下吗?
  • @Ignacio,在该链接问题的已接受答案中,超类在私有属性之后初始化。我认为这样做是可以的。

标签: python


【解决方案1】:

您应该阅读the code of the paren class。该类覆盖了许多特殊方法,包括__getattr__,这可能与您的问题有关。

【讨论】:

  • __getattr__ 仅被称为 fallbackself.w 首先在实例__dict__ 中查找,__getattr__ 只有在没有找到时才会查询。
  • 参见__getattr__ documentation当属性查找在通常的地方没有找到属性时调用(即它不是实例属性,也不是在@987654329的类树中找到@)
  • 所以@Martijn 你是说 getattr 不是问题吗?
  • @patchwork: 我是说__getattr__ 不可能是问题所在。
猜你喜欢
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 2012-08-04
  • 1970-01-01
  • 1970-01-01
  • 2013-12-13
相关资源
最近更新 更多