打印类的所有实例

打印类的所有实例

本文介绍了打印类的所有实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有了Python中的类,我如何定义一个函数来以函数中定义的格式打印类的每个单一实例?

With a class in Python, how do I define a function to print every single instance of the class in a format defined in the function?

推荐答案

我在这种情况下看到两个选项:

I see two options in this case:

import gc
for obj in gc.get_objects():
    if isinstance(obj, some_class):
        dome_something(obj)

这有一个缺点,当你有很多对象,但工作与你无法控制的类型非常慢。

This has the disadvantage of being very slow when you have a lot of objects, but works with types over which you have no control.

from collections import defaultdict
import weakref

class KeepRefs(object):
    __refs__ = defaultdict(list)
    def __init__(self):
        self.__refs__[self.__class__].append(weakref.ref(self))

    @classmethod
    def get_instances(cls):
        for inst_ref in cls.__refs__[cls]:
            inst = inst_ref()
            if inst is not None:
                yield inst

class X(KeepRefs):
    def __init__(self, name):
        super(X, self).__init__()
        self.name = name

x = X("x")
y = X("y")
for r in X.get_instances():
    print r.name
del y
for r in X.get_instances():
    print r.name

在这种情况下,所有引用都将作为弱引用存储在列表中。如果你经常创建和删除很多实例,你应该在迭代后清理weakrefs列表,否则会有很多cruft。

In this case, all the references get stored as a weak reference in a list. If you create and delete a lot of instances frequently, you should clean up the list of weakrefs after iteration, otherwise there's going to be a lot of cruft.

在这种情况下的另一个问题是,你必须确保调用基类构造函数。您还可以覆盖 __ new __ ,但只有第一个基类的 __ new __ 方法用于实例化。

Another problem in this case is that you have to make sure to call the base class constructor. You could also override __new__, but only the __new__ method of the first base class is used on instantiation. This also works only on types that are under your control.

编辑:根据特定格式打印所有实例的方法仍保留为一个练习,但它基本上只是 -loops的变体。

Edit: The method for printing all instances according to a specific format is left as an exercise, but it's basically just a variation on the for-loops.

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

08-04 02:28