PySide 信号“复制”行为

发布于 2024-12-07 01:08:53 字数 419 浏览 0 评论 0原文

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

输出:

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

“Loaded”仅打印一次(如预期;它是一个类变量),但为什么要创建 2 个信号实例(如果它也是一个类变量)?

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)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

快乐很简单 2024-12-14 01:08:53

它不会在创建类实例时打印,而是在执行类作用域时打印。这段代码将打印“Loaded”,即使我从未创建过“Test”的实例。

class Test:
    print "Loaded"

如果您想在类初始化时运行代码,请查看__init__()。此代码将在创建实例时打印“Loaded”,而不是在定义类本身时打印“Loaded”。

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

QT 的 QObject 元类似乎正在重写类属性,以防止在初始化类的新实例时出现重复信号。也许您可以像这样分配属性:

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

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

或者这样:

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)

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文