0

我正在使用 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''
4

1 回答 1

2

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

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

…</p>

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

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


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

  1. 你实际上想创建一个Component,而不是一个Entity
  2. 你想包装成forward_tick一个ComponentthisEntity可以包含的类型,或者
  3. 首先,您不想要Component面向 的设计。

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

如果您刚开始使用这种 [面向组件] 的设计,建议您通读The Pong Game 教程

于 2015-05-17T19:19:07.157 回答