Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

python - Usage of ObjectProperty class

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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[.]

(from the Kivy Property documentation)

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())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...