2015-05-17 59 views
0

我正在使用pysdl2库。 self.velocity会打印,但self.forward_tick抛出一个关键错误。sdl2实体的错误设置属性

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

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'' 

回答

2

从文档上component-based design with sdl2.ext,该Entity型是特殊的,并且没有按照正常的Python的成语。特别是,你不能只创建任意属性;你只能创建,其值是一个组件类型,其名称是该类型的小写版本属性:

Entity对象定义的应用对象和仅由基于组件的属性的。

...

Entity也requries要完全按照自己的组件类名称命名的属性,但在小写字母。

所以,当你尝试添加一个名为forward_tick属性,导致Entity.__setattr__去寻找一个名为世界的组件类型Forward_Tick类。它看起来通过查找self._world._componentypes[name],这是实际上引发异常的行,就像你在tracebacks中看到的那样。


不知道任何有关你的代码,你的设计比你给我们的小片段,我不能告诉你如何解决这个问题。但最有可能的,它是下列之一:

  1. 实际上,你想创造一个Component,不是Entity
  2. 你想在一个Component类型,这Entity可以包含包forward_tick,或
  3. 首先,您不希望采用面向Component的设计。

无论如何,作为文档说:

如果你只是这样的[面向组件的]设计入手,建议通过The Pong Game tutorial阅读。

相关问题