更新时间:2023-02-12 11:49:54
对于全局变量,仅使用赋值是不可能的.但是对于属性来说,它非常简单:只需使用属性(或 __getattr__/__setattr__
).这样可以有效地将赋值转换为函数调用,使您可以添加所需的任何其他行为:
For a global variable, this is not possible using assignment alone. But for an attribute it is quite simple: just use a property (or maybe __getattr__/__setattr__
). This effectively turns assignment into a function call, allowing you to add whatever additional behaviour you like:
class Foo(QWidget):
valueChanged = pyqtSignal(object)
def __init__(self, parent=None):
super(Foo, self).__init__(parent)
self._t = 0
@property
def t(self):
return self._t
@t.setter
def t(self, value):
self._t = value
self.valueChanged.emit(value)
现在您可以执行foo = Foo(); foo.t = 5
,并且在更改值之后将发出信号.
Now you can do foo = Foo(); foo.t = 5
and the signal will be emitted after the value has changed.