Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of ObjectProperty class

Tags:

python

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
like image 352
user2555406 Avatar asked Sep 02 '13 21:09

user2555406


People also ask

What is ObjectProperty in Python?

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.

What is numeric property in KIVY?

Validation for a NumericProperty will check that your value is a numeric type. This prevents many errors early on. Observer Pattern. You can specify what should happen when a property's value changes.

What is object property in Java?

The properties object contains key and value pair both as a string. The java. util. Properties class is the subclass of Hashtable. It can be used to get property value based on the property key.


1 Answers

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())
like image 58
Matthew Trevor Avatar answered Oct 22 '22 01:10

Matthew Trevor