ov1d1u ov1d1u - 1 month ago 9
Python Question

Notify parent instance about property change

I have these two classes:

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


and I use them like this:

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


I want
Buddy.status_updated
to be called when I modify the
message
property of
Status
. How to achieve this?

Answer Source

You'll have to store a reference back to the parent; python values do not track where they are stored (there can be multiple places that refer to your Status() instances):

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