擅长:python、mysql、java
<p>通过为对象定义自定义复制方法,可以显著提高性能:</p>
<pre><code>class Info(object):
__slots__ = ['x', 'y', 'z']
def swap(self):
newObj = self.copy()
newObj.x, newObj.y = self.y, self.x
return newObj
def copy(self):
clone = type(self)()
for slot in self.__slots__:
if hasattr(self, slot):
setattr(clone, slot, getattr(self, slot))
return clone
</code></pre>
<p>测试:</p>
^{pr2}$
<p>结果:</p>
<pre><code>copy.copy
1.5658336669985147
custom copy
0.4359149369993247
</code></pre>