擅长:python、mysql、java
<p>将<code>__iter__</code>添加到元类而不是类本身(假设Python 2.x):</p>
<pre><code>class Foo(object):
bar = "bar"
baz = 1
class __metaclass__(type):
def __iter__(self):
for attr in dir(self):
if not attr.startswith("__"):
yield attr
</code></pre>
<p>对于Python3.x,使用</p>
<pre><code>class MetaFoo(type):
def __iter__(self):
for attr in dir(self):
if not attr.startswith("__"):
yield attr
class Foo(metaclass=MetaFoo):
bar = "bar"
baz = 1
</code></pre>