Home > front end >  How to optimize traversal of instances in class methods?
How to optimize traversal of instances in class methods?

Time:10-05

I have a class MyClass and I have created 10 instances. I want to traverse the instances in the class method. The code is as follows.

Is there a more optimized method?

instance = {}


class MyClass:
    instances = range(10)

    def __init__(self, order):
        self.order = order

    @classmethod
    def cycle(cls):
        for i in cls.instances:
            print(instance[i].order)


for i in MyClass.instances:
    instance[i] = MyClass(i)

MyClass.cycle()

The result:

0
1
2
3
4
5
6
7
8
9

CodePudding user response:

Just use map:

instance = dict(zip(MyClass.instances, map(MyClass, MyClass.instances)))
MyClass.cycle()

Output:

0
1
2
3
4
5
6
7
8
9
  • Related