<p>我不相信有太多的理由来证明存储,除非每次的计算成本都很高。参见hpaulj的答案</p>
<p>然而,如果你真的想,你可以使用一个属性,甚至可以缓存它</p>
<pre><code>class MyList(list):
@property
def len_(self):
return len(self) #it's a list
or
_len_ = None
@property
def len_(self):
if self._len_ is None:
self._len_ = len(self)
return self._len_
def append(self, value):
self._len_ = None
super(MyList, self).append(value)
...and all other len-modifying methods also need to clear the cache.
</code></pre>
<p>同样,如果缓存它,则需要确保每次更改结果时都重置缓存。这也是您存储在实例变量上的想法的弱点——确保没有过时数据的额外复杂性可能只有在您确定这确实是一个性能瓶颈后才能接受</p>
<p>(顺便说一句,在您的示例中,对<code>multiple_numbers</code>使用<a href="https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument">mutable default argument</a>对这些问题没有帮助)。一般来说,如果sum/len取决于可变项的状态,那么存储/缓存计算是一个更糟糕的想法。i、 e.如果MyList引用的对象本身具有需要聚合的len/sum,那么MyList就没有任何缓存/存储的业务</p>
<p>在命名方面,我可能会选择a<a href="https://stackoverflow.com/a/39109501">semi-convention naming to avoid shadowing built-ins/conventional</a>名称,即添加a<code>_</code>:<code>cls</code>-><code>cls_</code>,<code>list</code>-><code>list_</code></p>