【问题标题】:Error setting attribute of an sdl2 Entitysdl2 实体的错误设置属性
【发布时间】:2015-05-17 19:00:16
【问题描述】:

我正在使用 pysdl2 库。 self.velocity 将打印,但 self.forward_tick 会抛出一个关键错误。

是什么导致只有部分自我属性被分配。我认为这与继承有关。

class Robot(sdl2.ext.Entity):
    def __init__(self, world, sprite, posx=0, posy=0):
        self.sprite = sprite
        self.sprite.position = posx, posy
        self.velocity = Velocity()
        self.forward_tick = 0
        self.go_forward = 0
        self.unit_forward = (1,0)
        print(self.velocity)
        print(self.forward_tick)

这是输出:

Collins-MacBook-Air:soccer_bots collinbell$ python test_simulation_world.py 
<simulation_world.Velocity object at 0x108ecb5c0>
Traceback (most recent call last):
  File "/Users/collinbell/.pyenv/versions/3.4.3/lib/python3.4/site-packages/sdl2/ext/ebs.py", line 53, in __getattr__
    ctype = self._world._componenttypes[name]
KeyError: 'forward_tick'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test_simulation_world.py", line 3, in <module>
    world = Simulation_World("Test Simulation", 1080, 720)
  File "/Users/collinbell/Programs/soccer_bots/simulation_world.py", line 100, in __init__
    self.player1 = Robot(self.world, sp_paddle1, 0, 250)
  File "/Users/collinbell/Programs/soccer_bots/simulation_world.py", line 22, in __init__
    print(self.forward_tick)
  File "/Users/collinbell/.pyenv/versions/3.4.3/lib/python3.4/site-packages/sdl2/ext/ebs.py", line 56, in __getattr__
    (self.__class__.__name__, name))
AttributeError: object ''Robot'' has no attribute ''forward_tick''

【问题讨论】:

    标签: python sdl-2 pysdl2


    【解决方案1】:

    component-based design with sdl2.ext 的文档中,Entity 类型是特殊的,并且不遵循普通的 Python 习惯用法。特别是,您不能只创建任意属性;您只能创建其值为组件类型且名称为该类型的小写版本的属性:

    Entity 对象定义应用程序内的对象并且仅包含基于组件的属性

    Entity 还要求将其属性命名为与其组件类名称完全相同,但使用小写字母。

    因此,当您尝试添加一个名为forward_tick 的属性时,这会导致Entity.__setattr__ 在世界的组件类型中寻找一个名为Forward_Tick 的类。它显然是通过查找self._world._componentypes[name] 来实现的,这实际上是引发异常的行,正如您在回溯中看到的那样。


    除了您向我们展示的小片段之外,我对您的代码和设计一无所知,我无法告诉您如何解决此问题。但最有可能的是以下情况之一:

    1. 您实际上想创建一个Component,而不是Entity
    2. 您想将forward_tick 封装在此Entity 可以包含的Component 类型中,或者
    3. 一开始你就不想要一个面向Component 的设计。

    无论如何,正如文档所说:

    如果你是刚入手这样的【面向组件】的设计,建议通读The Pong Game tutorial

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      相关资源
      最近更新 更多