擅长:python、mysql、java
<p>例如,对于n维向量</p>
<pre><code>class Vector:
def __init__(self, components):
self.components = components # components should be a list
def __add__(self, other):
assert len(other.components) == len(self.components)
added_components = []
for i in range(len(self.components)):
added_components.append(self.components[i] + other.components[i])
return Vector(added_components)
def dimensions(self):
return len(self.components)
</code></pre>
<p>这是可能的。请注意,<code>__add__</code>重写返回一个新的<code>Vector</code>实例,而不是您的案例中的<code>tuple</code>。然后同样地调整你的其他方法。你知道吗</p>
<p>有更多的'聪明'的方法<a href="https://stackoverflow.com/questions/11703064/how-do-i-add-two-lists-elements-into-one-list">adding elements from two lists, into a third</a>。如果性能是一个问题(或者在任何其他情况下只是一个练习,IMO),那么你真的不应该这样做。看看<a href="http://www.numpy.org/" rel="nofollow noreferrer">numpy</a>。你知道吗</p>