python - 通知父实例有关属性更改

标签 python class oop properties setter

我有这两个类:

class Status(object):
    def __init__(self):
        self._message = ''

    @property
    def message(self):
        return self._message

    @message.setter
    def message(self, value):
        self._message = value


class Buddy(object):
    def __init__(self, name):
        self.name = name
        self.status = Status()

    def status_updated(self):
        # this should be called when self.status.message is changed

我这样使用它们:

buddy = Buddy('John')
buddy.status.message = 'Hello world!'  # this should call Buddy.status_updated

我希望在修改 Statusmessage 属性时调用 Buddy.status_updated。如何实现?

最佳答案

您必须将引用存储返回给父级; python 值不跟踪它们的存储位置(可以有多个位置引用您的 Status() 实例):

class Status(object):
    def __init__(self, parent=None):
        self._message = ''
        self._parent = parent

    @property
    def message(self):
        return self._message

    @message.setter
    def message(self, value):
        self._message = value
        if self._parent is not None:
            self._parent.status_updated()


class Buddy(object):
    def __init__(self, name):
        self.name = name
        self.status = Status(self)

    def status_updated(self):
        # this should be called when self.status.message is changed

关于python - 通知父实例有关属性更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16626323/

相关文章:

python - Android 上的 Tensorflow 与 Python 绑定(bind)?

c++ - 类类型名称的重新声明

java - 在类之间传递字符串并跳过输入

python - 是否可以区分类函数 __add__ 中的运算符 += 和 +?

oop - 披萨建模

java - 具有多个可观察值的单个观察者

javascript - 我怎样才能在 OOP 方面做得更好?

python - 调用 Python 脚本时传递变量

python - 类型错误 : can't pickle PyCapsule objects

python - 根据现有数据帧的条件创建新数据帧