ObjectProperty类的用法 [英] Usage of ObjectProperty class
问题描述
我刚开始学习kivy,我对ObjectProperty类的用法以及如何将None作为参数感到非常困惑.有人可以解释一下吗?我在kivy教程中找到了它:
I Just started to learn kivy and I am very confused on the usage of the ObjectProperty class, and how it takes None as an argument. Could somebody explain it please? I found it in the kivy tutorial:
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
类的专门子类,因此它具有与其相同的初始化参数:
The Kivy Property
is a convenience class similar to Python's own property
but that also provides type checking, validation and events. ObjectProperty
is a specialised sub-class of the Property
class, so it has the same initialisation parameters as it:
默认情况下,属性始终采用默认值[.] 值必须是与属性类型一致的值.例如, 您无法将列表设置为StringProperty,因为StringProperty 将检查默认值.
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.
没有一个特殊情况:您可以将属性的默认值设置为 无,但之后无法将无"设置为属性.如果你真的 要做到这一点,必须使用allownone = True [.]
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[.]
(来自Kivy Property documentation
)
(from the Kivy Property documentation
)
在您的代码中,PongGame
具有一个ball
属性,该属性最初设置为None
,随后将被分配一个球形对象.这是在kv文件中定义的:
In your code, PongGame
has a ball
property that is initially set to None
and will later be assigned a ball object. This is defined in the kv file:
<PongGame>:
ball: pong_ball
PongBall:
id: pong_ball
center: self.parent.center
因为没有对象传递给初始化程序,所以可以将任何对象分配给该属性.您可以通过使用虚拟值对其进行初始化来将其限制为仅容纳球形物体:
Because no object was passed to the initialiser, any object can be assigned to that property. You could restrict it to only hold ball objects by initialising it with a dummy value:
ball = ObjectProperty(PongBall())
这篇关于ObjectProperty类的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!