[英]Python - Iterate over all classes
How can I iterate over a list of all classes loaded in memory? 如何遍历内存中加载的所有类的列表? I'm thinking of doing it for a backup, looking for all classes inheriting from db.Model (Google App Engine). 我正在考虑做备份,寻找从db.Model(Google App Engine)继承的所有类。
Thanks, Neal Walters 谢谢,Neal Walters
In "normal" Python, you can reach all objects via the gc.getobjects()
function of the gc
standard library module; 在“普通”Python中,您可以通过gc
标准库模块的gc.getobjects()
函数访问所有对象; it's then very easy to loop on them, checking which one are classes (rather than instances or anything else -- I do believe you mean instances of classes, but you can very easily get the classes themselves too if that's really what you want), etc. 然后很容易循环它们,检查哪一个是类(而不是实例或其他任何东西 - 我相信你的意思是类的实例 ,但如果那真的是你想要的话,你也很容易自己获得类),等等
Unfortunately, the gc
module in App Engine does NOT implement getobjects
-- which makes it extremely difficult to reach ALL classes. 不幸的是,App Engine中的gc
模块没有实现getobjects
- 这使得到达所有类非常困难。 For example, a class created by calling: 例如,通过调用创建的类:
def makeaclass():
class sic(object): pass
return sic
and hidden into a list somewhere, IS going to be very difficult to reach. 并隐藏在某个地方的列表中,很难达到。
But fortunately, since you say in your question's text that you only care about subclasses of db.Model
, that's even easier than gc
would allow: 但幸运的是,既然你在问题的文本中说你只关心db.Model
子类,那就比gc
更容易:
for amodel in db.Model.__subclasses__():
...
Just make sure you explicitly ignore such classes you don't care about, such as Expando
;-). 只需确保明确忽略您不关心的类,例如Expando
;-)。
Note that this DOES give you only and exactly the CLASSES, not the instances -- there is no similarly easy shortcut if those are what you're really after! 请注意,这个DOES只提供了CLASSES, 而不是实例 - 如果那些是您真正想要的,那么没有类似的简单快捷方式!
Classes are defined in modules. 类在模块中定义。 Modules are created by an import
statement. 模块由import
语句创建。
Modules are simply dictionaries. 模块只是字典。 If you want, you can use the dir(x)
function on a module named x
如果需要,可以在名为x
的模块上使用dir(x)
函数
Or you can use x.__dict__
on a module named x
. 或者您可以在名为x
的模块上使用x.__dict__
。
Based on S.Lott's response: This works if I omit the "if issubclass" except then I get classes I don't want. 基于S.Lott的回答:如果我省略“if issubclass”,那么这是有效的,除非我得到了我不想要的类。
import dbModels
self.response.out.write("<br/><br/>Class Names:</br/>")
for item in dbModels.__dict__:
if issubclass(item, db.Model):
self.response.out.write("<br/>" + item)
The above gives error: 以上给出了错误:
TypeError: issubclass() arg 1 must be a class TypeError:issubclass()arg 1必须是一个类
So it wants a classname as a parm, not an object name apparently. 所以它想要一个类名作为parm,而不是一个对象名。
Based on Alex's answer, this worked great: 根据Alex的回答,这很有用:
self.response.out.write("<br/><br/>Class Names Inheriting from db.Model:</br/>")
for item in db.Model.__subclasses__():
self.response.out.write("<br/>" + item.__name__)
Thanks to both! 谢谢你们两个!
Neal 尼尔
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.