【问题标题】:Dynamically creating @attribute.setter methods for all properties in class (Python)为类中的所有属性动态创建@attribute.setter 方法(Python)
【发布时间】:2015-09-02 01:18:22
【问题描述】:

我有别人这样写的代码:

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

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

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

    @attribute2.setter
    def attribue2(self, val):
        self.data.another_name2= val

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

【问题讨论】:

  • 如果函数内部只有 another_name 存在的地方,那么就没有明智的方法来提取它。

标签: python properties attributes setter


【解决方案1】:

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

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')

演示:

>>> 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

【讨论】:

  • 您正在修改MyClass。我希望有一个解决方案,这样我就不必修改其他人的课程。如果我这样做了,我无论如何都可以在他/她的类中编写@attr.setter 方法。不错的装饰器!
【解决方案2】:

这是问题的作者。我发现了一个非常简单的解决方案,但我不知道另一种方法。 (顺便说一下,我使用的是python 3.4。)

我将从我遇到的问题开始。

首先,我考虑过完全覆盖该属性,如下所示:

给定这个类

class A(object):
    def __init__(self):
        self._value = 42
    @property
    def value(self):
        return self._value

您可以通过执行以下操作完全覆盖该属性:

a = A()
A.value = 31 # This just redirects A.value from the @property to the int 31
a.value # Returns 31

问题是这是在类级别而不是在实例级别完成的,所以如果我创建 A 的新实例,就会发生这种情况:

a2 = A()
a.value # Returns 31, because the class itself was modified in the previous code block.

我希望它返回a2._value,因为a2 是A() 的全新实例,因此不应受到我对a 所做的影响。

解决这个问题的方法是用一个新属性覆盖A.value,而不是我想分配给实例_value 的任何东西。我了解到您可以使用特殊的getter、setter 和deleter 方法创建一个从旧属性实例化自身的新属性(请参阅here)。所以我可以覆盖 A 的 value 属性并通过这样做为它创建一个 setter:

def make_setter(name):
    def value_setter(self, val):
        setattr(self, name, val)
    return value_setter
my_setter = make_setter('_value')
A.value = A.value.setter(my_setter) # This takes the property defined in the above class and overwrites the setter with my_setter
setattr(A, 'value', getattr(A, 'value').setter(my_setter)) # This does the same thing as the line above I think so you only need one of them

只要原始类在原始类的属性定义中有一些非常简单的东西(在本例中只是return self._value),这一切都很好。然而,一旦你变得更复杂,像我这样的return self.data._value,事情就会变得很糟糕——就像@BrenBarn 在他对我的帖子的评论中所说的那样。我使用inspect.getsourcelines(A.value.fget) 函数来获取包含返回值的源代码行并对其进行解析。如果我未能解析字符串,我会引发异常。结果如下所示:

def make_setter(name, attrname=None):
    def setter(self, val):
        try:
            split_name = name.split('.')
            child_attr = getattr(self, split_name[0])
            for i in range(len(split_name)-2):
                child_attr = getattr(child_attr, split_name[i+1])
            setattr(child_attr, split_name[-1], val)
        except:
            raise Exception("Failed to set property attribute {0}".format(name))

它似乎可以工作,但可能存在错误。

现在的问题是,如果事情失败了怎么办?这取决于你,并且有点偏离这个问题。就个人而言,我做了一些令人讨厌的事情,包括创建一个继承自 A 的新类(我们称这个类为 B)。然后,如果 setter 为 A 工作,它将为 B 的实例工作,因为 A 是一个基类。但是,如果它不起作用(因为在 A 中定义的返回值有些讨厌),我在 class B 上运行了 settattr(B, name, val)。这通常会更改从创建的所有其他实例B(就像在这篇文章的第二个代码块中一样),但我使用 type('B', (A,), {}) 动态创建 B 并且只使用一次,因此更改类本身不会影响其他任何内容。

我认为这里有很多黑魔法类型的东西,但它非常酷,而且在白天用途广泛,所以我一直在使用它。这些都不是可复制粘贴的代码,但如果你理解它,那么你可以编写你的修改。

我真的希望/希望有更好的方法,但我不知道。也许从类创建的元类或描述符可以为您带来一些不错的魔力,但我对它们的了解还不够,无法确定。

欢迎评论!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-08
    • 2019-05-02
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多