Question

from PySide.QtCore import *

class Eggs(QObject):
    evt_spam = Signal()
    print "Loaded"

a = Eggs()
b = Eggs()
print a.evt_spam
print b.evt_spam
print a.evt_spam is b.evt_spam

outputs:

Loaded
<PySide.QtCore.Signal object at 0xa2ff1a0>
<PySide.QtCore.Signal object at 0xa2ff1b0>
False

"Loaded" only printing once (as expected; it is a class variable), but why are 2 instances of the signal being created (if it is also a class variable)?

Was it helpful?

Solution

It's not being printed when you create a class instance, but rather when the class scope is executed. This code will print "Loaded", even though I never made an instance of "Test".

class Test:
    print "Loaded"

If you want to run code when the class is initialized, take a look at __init__(). This code will print "Loaded" when an instance is made, instead of when the class itself is defined.

class Test:
    def __init__(self):
        print "Loaded"

QT's QObject metaclass appears to be rewriting the class attributes to prevent duplicate signals when you initialize a new instance of the class. Perhaps you can assign the attribute like this:

class Test(QObject):
    def __init__(self, signal):
        self.evt_spam = signal

sig = Signal()
a = Test(sig)
b = Test(sig)

Or this:

class Test(QObject):
    def signal(self, signal):
        self.evt_spam = evt_spam
        return self

evt_spam = Signal()
a = Test().signal(evt_spam)
b = Test().signal(evt_spam)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top