Python:使类可迭代 [英] Python: Make class iterable

查看:97
本文介绍了Python:使类可迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我继承了一个包含许多大类的项目,这些大类仅由类对象(整数,字符串等)组成.我希望能够检查是否存在属性,而无需手动定义属性列表.

I have inherited a project with many large classes constituent of nothing but class objects (integers, strings, etc). I'd like to be able to check if an attribute is present without needed to define a list of attributes manually.

是否可以使用标准语法使其本身可迭代的python class ?也就是说,我希望能够使用for attr in Foo:(甚至是if attr in Foo)对类的所有属性进行迭代,而无需首先创建类的实例.我想我可以通过定义__iter__来做到这一点,但是到目前为止,我还没有完全找到想要的东西.

Is it possible to make a python class iterable itself using the standard syntax? That is, I'd like to be able to iterate over all of a class's attributes using for attr in Foo: (or even if attr in Foo) without needing to create an instance of the class first. I think I can do this by defining __iter__, but so far I haven't quite managed what I'm looking for.

通过添加这样的__iter__方法已经实现了我想要的一些东西:

I've achieved some of what I want by adding an __iter__ method like so:

class Foo:
    bar = "bar"
    baz = 1
    @staticmethod
    def __iter__():
        return iter([attr for attr in dir(Foo) if attr[:2] != "__"])

但是,这并不能完全满足我的需求:

However, this does not quite accomplish what I'm looking for:

>>> for x in Foo:
...     print(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'classobj' object is not iterable

即使如此,这仍然可行:

Even so, this works:

>>> for x in Foo.__iter__():
...     print(x)
bar
baz

推荐答案

__iter__添加到元类而不是类本身(假设Python 2.x):

Add the __iter__ to the metaclass instead of the class itself (assuming Python 2.x):

class Foo(object):
    bar = "bar"
    baz = 1
    class __metaclass__(type):
        def __iter__(self):
            for attr in dir(self):
                if not attr.startswith("__"):
                    yield attr

对于Python 3.x,使用

For Python 3.x, use

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

这篇关于Python:使类可迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆