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

猴子修补Python属性设置器(和getter?),python,monkeypatching,Python,Monkeypatching,所以,猴子补丁非常棒,但是如果我想用猴子补丁一个@属性 例如,要修补方法,请执行以下操作: def new_method(): print('do stuff') SomeClass.some_method = new_method 但是,python中的属性会重新写入=符号 举个简单的例子,假设我想将x修改为4。我该怎么做呢 class MyClass(object): def __init__(self): self.__x = 3 @proper

所以,猴子补丁非常棒,但是如果我想用猴子补丁一个
@属性

例如,要修补方法,请执行以下操作:

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)
很好的尝试

三,

三,


使用
\u ClassName\u属性
,您可以访问该属性:

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

请参阅,特别是提到名称损坏的部分。

所问的问题与属性无关,而是与名称损坏有关,因为双下划线私有变量
self.\uux