PySide - class variable cannot be modified

I have a class named Panel which is derived from PySide.QtGui.QWidget. I want to keep track of how many panels I have created. To achieve this I introduce a class variable called count. The class definition snippet is as follows:

class Panel(QtGui.QWidget):
    count = 0
    def __init__(self, parent=None):
        super(Panel, self).__init__(parent)
        Panel.count += 1
        print(Panel.count)

but when I instantiate new panels, only a sequence of zeros is printed. But I would expect to see a sequence 1 2 3 ... In other words, the Panel.count += 1 seems to be ignored without any warning or error.

When I do the same with another class which is derived from normal Python's object rather than QWidget it works the way it is expected.

Any ideas why is that?

Upvotes: 4

Views: 238

Answers (4)

quazgar
quazgar

Reputation: 4632

Just an educated guess: By reassigning the class attribute, some strange behavior in QT's garbage collector might happen. Your observed behavior may be related to this issue.

Upvotes: 1

Starfight
Starfight

Reputation: 186

The problem is sometime it works, but sometime not. To palliate this problem, you can use global variable, but it's not a great solution.

Upvotes: 0

ekhumoro
ekhumoro

Reputation: 120568

It would be a bug in PySide if this didn't work.

Here is what I get when I run your code with PySide-1.2.1 (slightly corrected, because there's a missing self argument):

>>> from PySide import QtGui
>>> app = QtGui.QApplication([])
>>> class Panel(QtGui.QWidget):
...     count = 0
...     def __init__(self, parent=None):
...         super(Panel, self).__init__(parent)
...         Panel.count += 1
...         print(Panel.count)
... 
>>> p1 = Panel()
1
>>> p2 = Panel()
2
>>> p3 = Panel()
3
>>> Panel.count
3

Upvotes: 1

Joe
Joe

Reputation: 6757

In all likelihood this is an artifact of the Shiboken Python C++ binding generator PySide uses. This replaces the usual metaclass type with Shiboken.ObjectType (to check the metaclass of your type use print(Panel.__class__)). Metaclasses can drastically change the behavior of a class in python, just as it does in this case.

Upvotes: 0

Related Questions