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.S开发者_如何学Pythonignal 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)?
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)
精彩评论