擅长:python、mysql、java
<p>我不知道我的想法是否正确,但是<strong><a href="https://wiki.python.org/moin/Generators" rel="nofollow noreferrer">class generator pattern</a></strong>
并尝试添加序列bahaviour:</p>
<blockquote>
<p>if your class represents something that has a length, don't define a <strong><code>GetLength</code></strong> method; define the <code>__len__</code> method and use <code>len(instance)</code>.</p>
</blockquote>
<p>像这样:</p>
<pre><code>class firstn(object):
def __init__(self, n):
self.n = n
self.num, self.nums = 0, []
def __iter__(self):
return self
# Python 3 compatibility
def __next__(self):
return self.next()
# V - Something like this
def __len__(self):
return self.my_length
def next(self):
if self.num < self.n:
cur, self.num = self.num, self.num+1
return cur
else:
raise StopIteration()
</code></pre>