python - 将一个实例的属性属性绑定到另一个类

时间:2018-03-12 13:15:45

标签: python class dynamic properties descriptor

我想将一个类的实例上的特定属性/描述符绑定到另一个类的实例上的另一个属性(动态属性?)。类似的东西:

class Base(object):
    def __init__(self, value=None):
        self._value = value

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, value):
        self._value = value


class Child(Base):
    pass

class Parent(Base):
    def __init__(self, *args, **kwargs):
        super(Parent, self).__init__(*args, **kwargs)
        self.children = []

    def add_attrs(self, attr_child):
        for attr, child in attr_child:
            self.children.append(child)
            setattr(self, attr, child.value)

av = [("id_", Child(123)), ("name", Child("test"))]

p = Parent()
p.add_attrs(av)

assert p.name == p.children[-1].value

# at this point p.name == "test"
p.name = "abc"

# would like above to also set the child.value to "abc" 
assert p.name == p.children[-1].value

最终,如果我将名称设置为Child实例,我可以p.name.value,但我想知道是否可以这样做,因为我觉得它更好一些。我试过像:

def get_dict_attr(obj, attr):
    for obj in [obj] + obj.__class__.mro():
        if attr in obj.__dict__:
            return obj.__dict__[attr]
    raise AttributeError


class Parent(Base):
    def __init__(self, *args, **kwargs):
        super(Parent, self).__init__(*args, **kwargs)
        self.children = []

    def add_attrs(self, attr_child):
        for attr, child in attr_child:
            self.children.append(child)
            val = get_dict_attr(child, "value")
            setattr(self, attr, val)

但随后p.name == <property object at ... >。想知道这样的事情是否可能,并且没有任何迹象表明它是迄今为止。谢谢!

0 个答案:

没有答案