【问题标题】:Trigger a function when any property of an object changes with RxPy当对象的任何属性随 RxPy 发生变化时触发函数
【发布时间】:2023-04-02 02:39:01
【问题描述】:

在 RxPy 中,有没有类似 .NET 框架中的 INotifyPropertyChanged 提到的 here?我正在尝试向对象添加观察者,以便对象的任何属性发生变化,都会调用一个函数。

【问题讨论】:

    标签: python-3.x reactive-programming rx-py


    【解决方案1】:

    试试这样的:

    class A(object):
        def __init__(self):
            self._my_attr = None
            self.property_changed = Subject()
        ...
        @property
        def my_attr(self):
            return self._my_attr
    
        @my_attr.setter
        def my_attr(self, value):
            if value != self._my_attr:
                self._my_attr = value
                self.property_changed.on_next(('my_attr', value))
    
    a = A()
    a.property_changed.subscribe(print)
    a.my_attr = 1
    a.my_attr = 3
    

    【讨论】:

    • 有没有办法对文字变量执行此操作,例如保存字符串、列表或字典的变量 - 更具体地说是字典。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多