PyGTK properties versus python properties
When deriving from a GObject class in PyGTK, you can define GObject properties lik开发者_StackOverflow中文版e in C, using a __gproperties__
dict, and do_get_property
/do_set_property
methods, as described here in Sub-classing GObject in Python. Note that this was written before we had the @property
decorator in Python.
GObject properties have the advantage that you can connect to the object's notify::property-name
signal to receive a notification whenever the property changes. Other than that, is there any good reason to use GObject properties instead of Python's @property
decorator?
Why not use them? With the simplified version provided by the Python bindings, defining GObject properties is not that different to defining Python properties.
Having said that, there are a couple of advantages other than notification. The one that I've made use of in the past is property setting in gtk.Builder files. For example, in your UI file,
<object class="GtkImage" id="image">
<property name="stock">gtk-missing-image</property>
</object>
sets the stock
property on the Image object when constructed by the
Builder class; if you use GObject properties in
your custom widgets, you can take advantage of this too. This behaviour will be even
more useful with the advent of property binding support in Glade.
Another potential advantage is GObject properties' min/max limits and default values for integers and floats, which can sometimes be useful for UI-related properties.
Other than that, is there any good reason to use GObject properties instead of Python's @property decorator?
Not really. There's a lot of boilerplate for them, so unless I need the notify
signals, I write whatever I need in Python.
Having said that, it's fairly common that I'll think "I don't need notifications for this property" and then realise "actually, I don't need this property at all, then."
精彩评论