简体   繁体   English

根据类属性更改依赖对象

[英]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); 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 ). 然后,我想使用object_a.update(update_val)更新object_a.a属性,但同时对所有其他从属对象进行更新( object_b.b也将更新为update_val )。

How to do this in Python, is there a 'built-in' way? 如何在Python中执行此操作,是否有“内置”方式?

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 这是一个使用列表存储基础值但保留属性行为.a.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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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