如何在当前模块中获取类的所有实例 [英] How to obtain all instances of a class within the current module

查看:74
本文介绍了如何在当前模块中获取类的所有实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模块foo,它定义了一个类Foo,并实例化了该类的许多实例.

I have a module foo that defines a class Foo, and instantiates a number of instances of this class.

从其他模块中,我可以import foo并获得实例化的Foo对象的列表:

From other modules, I can import foo and obtain a list of the Foo objects instantiated by:

[getattr(foo,f) for f in dir(f) if isinstance(getattr(foo,f), foo.Foo)]

如果我可以在模块foo中执行此操作,将很方便.但是按照书面规定,在foo中,名称foo毫无意义,并且更改为self并没有帮助.

It would be convenient if I could do this from within the module foo. But as written, the name foo is meaningless inside foo, and changing to self doesn't help.

在此模块中是否可以使用自省来查找此类的所有实例?我希望有一种方法可以避免列出列表并附加每个实例.

Is there a way to use introspection within this module to find all instances of this class? I was hoping there was a way to avoid making a list and appending each instance.

推荐答案

目标:" import foo并获取由...实例化的Foo对象的列表."

goal: "import foo and obtain a list of the Foo objects instantiated by..."

您根本不需要内省.想象一下这是您的课程:

You don't need introspection at all. Imagine this is your class:

class Registered(object):
    _all = set()
    def __init__(self):
        self.__class__._all.add(self)

演示;实例化一堆对象并引用它们:

Demo; instantiate a bunch of objects and refer to them:

>>> Registered()
>>> Registered()
>>> Registered()

>>> Registered._all
{<__main__.Registered object at 0xcd3210>, <__main__.Registered object at 0xcd3150>, <__main__.Registered object at 0xcd31d0>}

由于您使用的是dir,因此,如果我对您的理解正确,那么您将尝试在当前模块的全局变量中查找所有对象.但是,它并不能真正让您获得当前模块中的所有对象,而只能获取绑定到变量的对象.如果那是您真正想要的,则可以执行{var for name,var in globals() if isinstance(var,Foo)}

Since you are using dir, if I understand you correctly, you are trying to find all the objects in the current module's global variables. However it doesn't really get you all the objects in the current module, only those bound to variables. If that's what you really want, you can do {var for name,var in globals() if isinstance(var,Foo)}

如果这不是您真正想要的,则可以修改上面的内容以跟踪通过inspect.currentframe().f_back.f_globals或其他对象定义了该模块的模块,但这将阻止您使用在foo.py或inc中定义的工厂函数.其他模块.

If that's not what you really want, you can modify the above to keep track of the module the object was defined in via inspect.currentframe().f_back.f_globals or something, but this would prevent you from using factory functions defined in foo.py or in other modules.

如果您实际上试图获取模块中创建的所有内容的所有实例,那么这表明存在严重的编码问题;考虑也许在该模块中编写一个工厂函数包装器,除了传递初始化args并返回结果,并跟踪初始化对象之外,什么都不做.

If you are actually trying to get all instances of something created in a module, this is a sign of a serious coding issue however; consider perhaps writing a factory function wrapper in that module, which does nothing except pass along the initialization args and return the result, keeping track of initialized objects.

这篇关于如何在当前模块中获取类的所有实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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