Can I iterate over a class in Python?

后端 未结 4 600
后悔当初
后悔当初 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:07

    Try this:

    You can create a list with a global scope, define a list in the main module as follows:

    fooList = []
    

    Then add:

    class Foo:
      def __init__(self):
        fooList.append(self)
    

    to the init of the foo class

    Then everytime you create an instance of the Foo class it will be added to the fooList list.

    Now all you have to do is iterate through the array of objects like this

    for f in fooList:
        f.doSomething()
    

提交回复
热议问题