【问题标题】:How to optimize traversal of instances in class methods?如何优化类方法中实例的遍历?
【发布时间】:2021-11-25 10:23:10
【问题描述】:

我查看了每个实例的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()

我有一个班级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

【问题讨论】:

  • 我不确定我是否理解
  • @U12-Forward 我编辑了我的问题。
  • 如何更优化?
  • @RobbyCornelissen 能不能再优化一下?
  • 什么意思,更优化了?快点?更少的内存使用?更少的代码行数?

标签: python class methods instance


【解决方案1】:

只需使用map:

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

输出:

0
1
2
3
4
5
6
7
8
9

【讨论】:

  • 我需要的变量instance是dict,怎么办?
  • @jaried 编辑我的
猜你喜欢
  • 2018-08-17
  • 2020-11-21
  • 2010-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多