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

时间:2015-02-12 01:25:12

标签: python monkeypatching

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

例如,要修补方法:

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

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

快速举例,假设我想将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)
  

很好的尝试

     

3

     

3

1 个答案:

答案 0 :(得分:2)

使用_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,特别是提及名称修改的部分。