为类中的所有属性动态创建@ attribute.setter方法(Python)

Jas*_*nis 2 python setter attributes properties

我有其他人这样写的代码:

class MyClass(object):
    def __init__(self, data):
        self.data = data

    @property
    def attribute1(self):
        return self.data.another_name1

    @property
    def attribute2(self):
        return self.data.another_name2
Run Code Online (Sandbox Code Playgroud)

而且我想在运行时自动创建相应的属性设置器,因此不必修改其他人的代码。属性设置器应如下所示:

    @attribute1.setter
    def attribue1(self, val):
        self.data.another_name1= val

    @attribute2.setter
    def attribue2(self, val):
        self.data.another_name2= val
Run Code Online (Sandbox Code Playgroud)

如何动态地将这些setter方法添加到类中?

Ash*_*ary 5

您可以像这样编写自定义描述符:

from operator import attrgetter


class CustomProperty(object):
    def __init__(self, attr):
        self.attr = attr

    def __get__(self, ins, type):
        print 'inside __get__'
        if ins is None:
            return self
        else:
            return attrgetter(self.attr)(ins)

    def __set__(self, ins, value):
        print 'inside __set__'
        head, tail = self.attr.rsplit('.', 1)
        obj = attrgetter(head)(ins)
        setattr(obj, tail, value)


class MyClass(object):
    def __init__(self, data):
        self.data = data

    attribute1 = CustomProperty('data.another_name1')
    attribute2 = CustomProperty('data.another_name2')
Run Code Online (Sandbox Code Playgroud)

演示:

>>> class Foo():
...         pass
...
>>> bar = MyClass(Foo())
>>>
>>> bar.attribute1 = 10
inside __set__
>>> bar.attribute2 = 20
inside __set__
>>> bar.attribute1
inside __get__
10
>>> bar.attribute2
inside __get__
20
>>> bar.data.another_name1
10
>>> bar.data.another_name2
20
Run Code Online (Sandbox Code Playgroud)