python - 在运行时覆盖 __setattr__

标签 python

我知道在 Python 中可以在运行时向类添加方法:

class Test:
    def __init__(self):
        self.a=5

test=Test()

import types
def foo(self):
    print self.a
test.foo = types.MethodType(foo, test)
test.foo() #prints 5

而且我也知道可以覆盖类定义中的默认 setattr:

class Test:
    def __init__(self):
        self.a=5
    def __setattr__(self,name,value):
        print "Possibility disabled for the sake of this test"

test=Test() #prints the message from the custom method called inside __init__

但是,似乎无法在运行时覆盖 setattr:

class Test:
    def __init__(self):
        self.a=5

test=Test()

import types
def __setattr__(self,name,value):
    print "Possibility disabled for the sake of this test"
test.__setattr__ = types.MethodType(__setattr__, test)
test.a=10 #does the assignment instead of calling the custom method

在后两种情况下,dir(test) 还报告方法 setattr。但是,虽然在第一种情况下它可以正常工作,但在第二种情况下却不能。请注意,我也可以显式调用它,在这种情况下它可以工作。似乎是这样,虽然已经定义了方法,但尚未正确映射以覆盖默认的赋值方法。我错过了什么吗?

顺便说一句,我正在使用 Python 2.7。这个问题主要是学术性的,因为从程序设计的角度来看,做这样的事情可能不是一个好主意,但它仍然值得一个答案——尽管我进行了搜索,但我无法在任何地方找到它的记录。

最佳答案

它记录在 Data model 中,“类实例”部分:

Attribute assignments and deletions update the instance’s dictionary, never a class’s dictionary. If the class has a __setattr__() or __delattr__() method, this is called instead of updating the instance dictionary directly.

所以无论是旧式还是新式,这两个检查总是针对类型而不是实例进行。

关于python - 在运行时覆盖 __setattr__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13408372/

相关文章:

python - PyCUDA:查询设备状态(特别是内存)

python - 在 Python 3 中识别按键的代码

python - 为什么 Tkinter Entry 的 get 函数什么都不返回?

python - 高级数组/数据帧切片(numpy/pandas)

python - 无法在我的应用程序 models.py 中将 auth_user 模型主键设置为外键

python - lxml etree.parse 内存分配错误

python - Pandas 数据帧 : apply function to all columns

python - Pandas pytable : how to specify min_itemsize of the elements of a MultiIndex

python - python socket-如何将流保存到文件

python - 如何通过Python文件在控制台运行函数?