如何优化 class 方法中的实例遍历?

How to optimize traversal of instances in class methods?

我查看了每个实例的dict instance的内存地址,指向同一个地址,所以用class instance存放相关的实例名更方便

这才是我真正想要的。

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()

我有一个 class MyClass 并且我创建了 10 个实例。我想遍历 class 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()

结果:

0
1
2
3
4
5
6
7
8
9

只需使用map:

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

输出:

0
1
2
3
4
5
6
7
8
9