我刚开始学习kivy,我对ObjectProperty类的用法以及它如何将None作为参数感到非常困惑。有人可以解释一下吗?我在kivy教程中找到了它:
class PongGame(Widget):
ball = ObjectProperty(None)
def update(self, dt):
self.ball.move()
# bounce off top and bottom
if (self.ball.y < 0) or (self.ball.top > self.height):
self.ball.velocity_y *= -1
# bounce off left and right
if (self.ball.x < 0) or (self.ball.right > self.width):
self.ball.velocity_x *= -1
最佳答案
Kivy Property
是一个类似于 Python 自己的 property
的便利类,但它还提供类型检查、验证和事件。 ObjectProperty
是 Property
类的特殊子类,因此它具有与其相同的初始化参数:
By default, a Property always takes a default value[.] The default value must be a value that agrees with the Property type. For example, you can’t set a list to a StringProperty, because the StringProperty will check the default value.
None is a special case: you can set the default value of a Property to None, but you can’t set None to a property afterward. If you really want to do that, you must declare the Property with allownone=True[.]
(来自基维Property documentation
)
在您的代码中,PongGame
有一个 ball
属性,该属性最初设置为 None
,稍后将分配一个 ball 对象。这是在 kv 文件中定义的:
<PongGame>:
ball: pong_ball
PongBall:
id: pong_ball
center: self.parent.center
因为没有对象被传递给初始化器,任何对象都可以分配给该属性。您可以通过使用虚拟值对其进行初始化来将其限制为仅容纳球对象:
ball = ObjectProperty(PongBall())
关于python - ObjectProperty 类的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18580794/