我刚开始学习 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:
默认情况下,属性始终采用默认值[.] 默认值value 必须是与 Property 类型一致的值.例如,您不能将列表设置为 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.
None 是一种特殊情况:您可以将 Property 的默认值设置为无,但您不能在之后将 None 设置为属性.如果你真的想要这样做,您必须使用 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 属性文档
)
(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 类的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!