打印一个类的所有实例 [英] Printing all instances of a class

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

问题描述

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

解决方案

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

垃圾收集器

导入gc对于 gc.get_objects() 中的 obj:如果 isinstance(obj, some_class):dome_something(对象)

当你有很多对象时,它的缺点是非常慢,但适用于你无法控制的类型.

使用mixin和weakrefs

from collections import defaultdict导入弱引用类KeepRefs(对象):__refs__ = defaultdict(list)def __init__(self):self.__refs__[self.__class__].append(weakref.ref(self))@类方法def get_instances(cls):对于 cls.__refs__[cls] 中的 inst_ref:inst = inst_ref()如果 inst 不是 None:收益率X 类(KeepRefs):def __init__(self, name):super(X, self).__init__()self.name = 姓名x = X("x")y = X("y")对于 X.get_instances() 中的 r:打印 r.name延迟对于 X.get_instances() 中的 r:打印 r.name

在这种情况下,所有引用都作为弱引用存储在列表中.如果频繁创建和删除大量实例,则应在迭代后清理弱引用列表,否则会出现很多杂乱无章的情况.

这种情况下的另一个问题是您必须确保调用基类构造函数.您也可以覆盖 __new__,但在实例化时仅使用第一个基类的 __new__ 方法.这也仅适用于受您控制的类型.

编辑:根据特定格式打印所有实例的方法留作练习,但它基本上只是for循环的变体.

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:

Garbage collector

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.

Use a mixin and weakrefs

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

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.

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.

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.

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

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