Python 将添加委派给自定义类的就地添加是一个好主意吗?
给定一个需要支持加法的自定义类,是否有任何理由不将uuu add uuu方法委托给uuu iadd u,以便:Python 将添加委派给自定义类的就地添加是一个好主意吗?,python,oop,operator-overloading,Python,Oop,Operator Overloading,给定一个需要支持加法的自定义类,是否有任何理由不将uuu add uuu方法委托给uuu iadd u,以便: def __add__(self, other): if not self.comparable(other): raise ValueError("Objects cannot be added!") temp = copy.deepcopy(self) temp += other return temp def __iadd__
def __add__(self, other):
if not self.comparable(other):
raise ValueError("Objects cannot be added!")
temp = copy.deepcopy(self)
temp += other
return temp
def __iadd__(self, other):
if not self.comparable(other):
raise ValueError("Objects cannot be added!")
self.x += other.x
self.y += other.y
# ... whatever else addition voodoo
除了copy.deepcopy可能是内存的一个问题之外,我想不出任何东西,但是由于加法应该返回一个新对象并保持self不变,所以我不确定它是否可以避免。另一种方法是用构造函数实例化一个新对象,如果类有许多可变变量,那么这并不是一个很好的选择。在我的例子中,这是一个随机模型,它是从一整块训练数据生成的,所以更容易得到一个副本
以上所有定义都符合要求,但我在任何教程中都没有看到这两种方法之间的这种依赖关系,这让我有点怀疑
这是不是危险或不良的实践?
< P>这当然是C++中自然和推荐的方式。 另一方面,如果您有基本整数或字符串类型之类的不可变对象,那么您就不会有uuu iadd uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu 如果没有uuu iadd uuuuuuuux,x+=y将调用x.uuu add uuuuuuuy或y.uuu radd uuux,然后将结果分配给x