在我遇到链接到 Python documentation 的this other SO post 之前,这里关于不从就地操作返回的答案让我有些困惑(我以为我读过,但一定只是略读)。参考就地运营商的文档说:
这些方法应该尝试就地执行操作(修改 self)并返回结果(可以是但不一定是 self)。
当我尝试使用就地操作而不返回self 时,它变成了None。在这个例子中,它会说vars 需要一个带有__dict__ 的对象。查看self 的类型显示None。
# Skipping type enforcement and such.
from copy import copy
import operator
import imported_utility # example.
class A:
def __init__(self, a, b):
self.a = a
self.b = b
def one(self, scaler):
self *= scaler
return imported_utility(vars(self))
def two(self, scaler):
tmp = self * scaler
return imported_utility(vars(tmp))
def three(self, scaler):
return imported_utility(vars(self * scaler))
# ... addition, subtraction, etc.; as below.
def __mul__(self, other):
tmp = copy(self)
tmp._inplace_operation(other, operator.imul)
return tmp
def __imul__(self, other): # fails.
self._inplace_operation(other, operator.imul)
# Fails for __imul__.
def _inplace_operation(self, other, op):
self.a = op(self.a, other)
self.b = op(self.b, other)
* 有效(二和三),但 *=(一)直到 self 返回。
def __imul__(self, other):
return self._inplace_operation(other, operator.imul)
def _inplace_operation(self, other, op):
self.a = op(self.a, other)
self.b = op(self.b, other)
return self
我不完全理解这种行为,但对引用帖子的后续评论说,没有返回 self,就地方法真正修改了该对象,但将其名称重新绑定到 None。除非返回 self,否则 Python 不知道要重新绑定到什么。通过保持对对象的单独引用可以看到这种行为。