【问题标题】:Monkey patching Python Property setters (and getters?)猴子修补 Python 属性设置器(和获取器?)
【发布时间】:2015-02-12 01:25:11
【问题描述】:

所以,猴子补丁非常棒,但是如果我想给 @property 猴子补丁呢?

例如,给一个方法打补丁:

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)

不错的尝试

3

3

【问题讨论】:

  • 所问的问题与属性没有任何关系,但由于双下划线私有变量self.__x 而与名称修改有关

标签: python monkeypatching


【解决方案1】:

使用_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,尤其是提到名称修改的部分。

【讨论】:

    猜你喜欢
    • 2014-03-05
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 2012-03-13
    • 2013-12-26
    • 2012-06-14
    • 2012-03-29
    相关资源
    最近更新 更多