Object and class introspection
Both Python and Qt offer a great deal of
object introspection functionality — that is, methods of
determining at runtime what kind of class an object is an
instance of, or what methods an object implements. It has often
been difficult to make Python and Qt introspection mesh well.
One example is the
QObject.className(),
which returns the name of the class of an object. Until PyQt
version 2.5, this function always returned
QObject, instead of the Python class
name. Since that version, however, it returns the true class
name:
Example 9-10. Object introspection using Qt
Python 2.1 (#1, Apr 17 2001, 20:50:35) [GCC 2.95.2 19991024
(release)] on linux2 Type "copyright", "credits" or "license"
for more information.
>>> from qt import *
>>> t=QTimer()
>>> t.className() 'QTimer'
>>> class A(QTimer): pass ...
>>> a=A()
>>> a.className() 'A'
>>> a.inherits('QTimer') 1
For interesting Python introspection functions you should
consult the Python language reference — but the equivalent
using Python idioms of the above session would be:
Example 9-11. Object introspection using Python
>>> t.__class__ <class qt.QTimer at 0x8232cc4>
>>> a.__class__ <class __main__.A at 0x826c2ac>
>>> a.__class__.__bases__ (<class qt.QTimer at
0x8232cc4>,)
Object introspection is especially useful if you dabble in
the black art known as meta-programming — that is,
creating a program that run-time constructs some of the classes
it needs. Heaps of fun — but not always innocent
fun.