python 来自http://stackoverflow.com/questions/328851/printing-all-instances-of-a-class

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 来自http://stackoverflow.com/questions/328851/printing-all-instances-of-a-class相关的知识,希望对你有一定的参考价值。

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

以上是关于python 来自http://stackoverflow.com/questions/328851/printing-all-instances-of-a-class的主要内容,如果未能解决你的问题,请参考以下文章

python 来自Python的Git pull

python 来自Python的os文件系统

一封来自“Python”的信

来自 Black Hat Python 书的 Python 嗅探

“路径 python3(来自 --python=python3)不存在”错误

python Python装饰模板(来自“Head First Python ed.2”)