跟踪python中的实例 [英] Keep track of instances in python

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

问题描述

在程序结束时,我想将一个类的所有实例中的特定变量加载到字典中。



例如:

  class Foo():
__init __(self):
x = {}

foo1 = Foo()
foo2 = Foo()
foo ...等。假设实例的数量会有所不同,我想要每个Foo()实例的x dict,加载到一个新的dict。



我在SO中看到的例子假定已经有实例列表。

 类A(对象):
instances = []

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

在程序结束时,您可以创建如下的字典:

  foo_vars = {id(instance):instance.foo例如在A.instances中} 
pre>

只有一个列表:

 > > a = A(1)
>>>> b = A(2)
>>>> A.instances
[< __ main __。一个对象在0x1004d44d0>,< __ main __。一个对象在0x1004d4510>]
>>> id(A.instances)
4299683456
>>>> id(a.instances)
4299683456
>>>> id(b.instances)
4299683456


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

For example:

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

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

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?

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}

There is only one list:

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

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

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