Can I iterate over a class in Python?

后端 未结 4 591
后悔当初
后悔当初 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 03:55

    You can create a class list and then call append in the init method as follows:

    class Planet:
      planets_list = []
    
      def __init__(self, name):
         self.name = name
         self.planets_list.append(self)
    

    Usage:

    p1 = Planet("earth")
    p2 = Planet("uranus")
    
    for i in Planet.planets_list:
        print(i.name)
    

提交回复
热议问题