Can I iterate over a class in Python?

后端 未结 4 597
后悔当初
后悔当初 2020-12-29 03:21

I have a class that keeps track of its instances in a class variable, something like this:

class Foo:
    by_id = {}

    def __init__(self, id):
        sel         


        
4条回答
  •  星月不相逢
    2020-12-29 04:22

    Magic methods are always looked up on the class, so adding __iter__ to the class won't make it iterable. However the class is an instance of its metaclass, so the metaclass is the correct place to define the __iter__ method.

    class FooMeta(type):
        def __iter__(self):
            return self.by_id.iteritems()
    
    class Foo:
        __metaclass__ = FooMeta
        ...
    

提交回复
热议问题