Home > Enterprise >  Iterate through class objects
Iterate through class objects

Time:11-09

I have defined class this way:

class Vehicules(object):
    class Car(object):
        INSTANCES = 5
        WIDTH = 5
        HEIGHT = 4

    class Bike(object):
        INSTANCES = 3
        WIDTH = 3
        HEIGHT = 4

    class Pedestrian(object):
        INSTANCES = 2
        WIDTH = 2
        HEIGHT = 4

I'm looking for a way to execute a script that goes along these lines:

for obj in Vehicules:
     print(obj.INSTANCES)

Any idea how to achieve that please?

CodePudding user response:

class Vehicules(object):
    class Car(object):
        INSTANCES = 5
        WIDTH = 5
        HEIGHT = 4

    class Bike(object):
        INSTANCES = 3
        WIDTH = 3
        HEIGHT = 4

    class Pedestrian(object):
        INSTANCES = 2
        WIDTH = 2
        HEIGHT = 4
all_vehicle_classes = [c for c in vars(Vehicules).values() if isinstance(c, type(Vehicules))]
for inner_class in all_vehicle_classes:
    print(inner_class.INSTANCES)

F.Y.I: Inner classes are generally avoided.

  • Related