Iterating over object instances of a given class in Python

前端 未结 3 1402
轻奢々
轻奢々 2020-12-13 02:46

Given a class that keeps a registry of its Objects:

class Person(object):
   __registry = []

   def __init__(self, name):
       self.__registry.append(self         


        
3条回答
  •  被撕碎了的回忆
    2020-12-13 03:22

    You can make your class object iterable with a simple metaclass.

    class IterRegistry(type):
        def __iter__(cls):
            return iter(cls._registry)
    
    class Person(object):
        __metaclass__ = IterRegistry
        _registry = []
    
        def __init__(self, name):
            self._registry.append(self)
            self.name = name
    

    (I have also changed __registry to _registry to make it easier to access from the metaclass). Then,

    >>> p = Person('John')
    >>> p2 = Person('Mary')
    >>> for personobject in Person:
    ...     print personobject
    ...
    
    
    

提交回复
热议问题