Search code examples
pythonclassmethodsinstance

How to optimize traversal of instances in class methods?


I checked the memory address of the dict instance of each instance, pointing to the same address, so it is more convenient to use the class instance to store the related instance name.

This is what I really wanted.

class MyClass:
    lens = range(10)
    instance = {}

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

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

    @classmethod
    def cls_init(cls):
        for i in cls.lens:
            cls.instance[i] = cls(i)


MyClass.cls_init()
MyClass.cycle()

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

Solution

  • 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