擅长:python、mysql、java
<p>{1}而不是使用^ 1>方法来获得不变性:</p>
<pre><code>import collections as co
# this will create a class with five attributes
class Info(co.namedtuple('BaseInfo', 'x y a b c')):
__slots__ = ()
def setDirection(self, x, y):
return self._replace(x=x, y=y)
def swap(self):
return self._replace(x=self.y, y=self.x)
</code></pre>
<p>我已经对这两个类中<code>swap()</code>方法的性能进行了基准测试,从<code>namedtuple</code>派生的类在Python3中大约快3-4倍。以下是基准代码:</p>
^{pr2}$
<p>结果:</p>
<pre><code>Built from scratch
1.8578372709998803
Derived from namedtuple
0.520611657999325
</code></pre>