简体   繁体   中英

Change dependent objects based on a class attribute

For example, if I have two classes :

class A:
  def __init__(self):
     self.a = 1;

  def update(self, val):
     self.a = val;
class B:
  def __init__(self, default = A()):
     self.b = default.a;

Using them : object_a = A(); object_b = B(object_a); object_a = A(); object_b = B(object_a);

Then, I would like to update the object_a.a attribute using object_a.update(update_val) but also concurrently update at all other dependent objects ( object_b.b will also be updated to update_val ).

How to do this in Python, is there a 'built-in' way?

I already have some manual solutions in mind, such as:

class A:
  def __init__(self):
     self.a = 1;
     self.dependent = None; 

  def update(self, val):
     self.a = val;
     if self.dependent != None:
        self.dependent.b = self.a;

class B:
  def __init__(self, default = A()):
     default.dependent = self;
     self.b = default.a;

One way to accomplish what you are asking is use a mutable object, such as a list, to store the attribute's data. Since the objects will reference the list, changing the values of the list will be shared to both objects.

Here is a version that uses a list to store the underlying value, but maintains the attribute behavior .a and .b

class A:
    def __init__(self):
        self._a = [1]

    def update(self, val):
        self._a[0] = val

    @property
    def a(self):
        return self._a[0]

class B:
    def __init__(self, default):
        self._b = default._a

    @property
    def b(self):
        return self._b[0]

a = A()
b = B(a)
a.update(4)

b.b
# returns:
4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM