繁体   English   中英

sdl2实体的错误设置属性

[英]Error setting attribute of an sdl2 Entity

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

使用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教程

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM