問題描述
我剛開始學(xué)習(xí) kivy,我對(duì) ObjectProperty 類的用法以及它如何將 None 作為參數(shù)感到非常困惑.有人可以解釋一下嗎?我在 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
是一個(gè)類似于 Python 自己的 property
的便利類,但也提供類型檢查,驗(yàn)證和事件.ObjectProperty
是 Property
類的一個(gè)特殊子類,因此它具有與它相同的初始化參數(shù):
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:
默認(rèn)情況下,屬性始終采用默認(rèn)值[.] 默認(rèn)值value 必須是與 Property 類型一致的值.例如,您不能將列表設(shè)置為 StringProperty,因?yàn)?StringProperty將檢查默認(rèn)值.
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 的默認(rèn)值設(shè)置為無,但您不能在之后將 None 設(shè)置為屬性.如果你真的想要這樣做,您必須使用 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
有一個(gè) ball
屬性,該屬性最初設(shè)置為 None
,稍后將被分配一個(gè)球?qū)ο?這是在 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
因?yàn)闆]有對(duì)象被傳遞給初始化器,所以 任何 對(duì)象都可以分配給該屬性.您可以通過使用虛擬值對(duì)其進(jìn)行初始化來將其限制為僅容納球?qū)ο?
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())
這篇關(guān)于ObjectProperty 類的使用的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!