猴子修补 Python 属性 设置器(和吸气器?)

Monkey patching Python Property setters (and getters?)

所以,猴子补丁非常棒,但是如果我想猴子补丁 @property 怎么办?

例如给monkey patch一个方法:

def new_method():
    print('do stuff')
SomeClass.some_method = new_method

然而,python 中的属性重写了 = 符号。

举个简单的例子,假设我想将 x 修改为 4。我该怎么做呢?:

class MyClass(object):
    def __init__(self):
        self.__x = 3

    @property
    def x(self):
        return self.__x

    @x.setter
    def x(self, value):
        if value != 3:
            print('Nice try')
        else:
            self.__x = value

foo = MyClass()
foo.x = 4
print(foo.x)
foo.__x = 4
print(foo.x)

Nice try

3

3

使用_ClassName__attribute,您可以访问属性:

>>> class MyClass(object):
...     def __init__(self):
...         self.__x = 3
...     @property
...     def x(self):
...         return self.__x
...     @x.setter
...     def x(self, value):
...         if value != 3:
...             print('Nice try')
...         else:
...             self.__x = value
... 
>>> foo = MyClass()
>>> foo._MyClass__x = 4
>>> foo.x
4

参见 Private Variables and Class-local References - Python tutorial,尤其是提到 name mangling 的部分。