确定描述符中的短运算符(+= like)用法

Determine short operators (+= like) usage in descriptor

我现在正在尝试为模型字段创建一个描述符 class 以保存其修改历史。

我可以通过重写 getattr 来确定何时对字段值调用了某些方法:

def __getattr__(self, attr):
    print(attr)
    return super().__getattr__(attr)

而且我可以看到重写方法的参数:

def __add__(self, other):
    print(self, other)
    return super().__add__(other)

问题是 += 运算符只是一个语法糖:

foo = foo + other

所以我无法将 += 处理为单个方法调用,它触发 __add__ 然后 __set__。我能否确定该值并未完全被新值取代,而是 added/multiplied/divided 等?

使用__iadd__

For instance, if x is an instance of a class with an __iadd__() method, x += y is equivalent to x = x.__iadd__(y) . Otherwise, x.__add__(y) and y.__radd__(x) are considered, as with the evaluation of x + y.