如何跟踪类实例? [英] How to keep track of class instances?

查看:77
本文介绍了如何跟踪类实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在程序的最后,我希望将类的所有实例中的特定变量加载到字典中.

Toward the end of a program I'm looking to load a specific variable from all the instances of a class into a dictionary.

例如:

class Foo():
    __init__(self):
    x = {}

foo1 = Foo()
foo2 = Foo()
foo...etc.

让我们说实例的数量会有所不同,我希望将Foo()的每个实例的x dict加载到一个新的dict中.我该怎么办?

Let's say the number of instances will vary and I want the x dict from each instance of Foo() loaded into a new dict. How would I do that?

我在SO中看到的示例假定一个已经具有实例列表.

The examples I've seen in SO assume one already has the list of instances.

推荐答案

跟踪实例的一种方法是使用类变量:

One way to keep track of instances is with a class variable:

class A(object):
    instances = []

    def __init__(self, foo):
        self.foo = foo
        A.instances.append(self)

在程序结束时,您可以像这样创建字典:

At the end of the program, you can create your dict like this:

foo_vars = {id(instance): instance.foo for instance in A.instances}

只有一个列表:

>>> a = A(1)
>>> b = A(2)
>>> A.instances
[<__main__.A object at 0x1004d44d0>, <__main__.A object at 0x1004d4510>]
>>> id(A.instances)
4299683456
>>> id(a.instances)
4299683456    
>>> id(b.instances)
4299683456    

这篇关于如何跟踪类实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆