Get all user defined classes in a file

时间:2015-06-14 18:32:04

标签: python django

If I have a file, say first.py, which looks like this -

class Person(object):
    pass

class Dog(object):
    pass

and I have a second file, second.py. How can I get all the classes that were defined in first.py in second.py?

Perhaps I should mention that the use-case I'm trying to implement is similar to the one that happens when initializing models in Django - When I run the manage.py sql myapp command, I assume Django goes through all my models in models.py and generates an SQL query for them.

So what I'm trying to do is similar to what Django does when it takes all models defined in models.py.

How can I get all the user defined classes from a file? (Unless there's a smarter way to do what Django does)

Thanks in advance!

2 个答案:

答案 0 :(得分:3)

如果你有一个文件first.py,在second.py中,你必须编写以下代码来返回first.py中所有用户定义的类:

import first
from types import *
userDefinedClasses = [i for i in dir(first) if type(getattr(first, i)) is TypeType]

在您的简单示例中,预定义first.py,dir(first)将返回列表['Dog', 'Person', '__builtins__', '__doc__', '__file__', '__name__', '__package__']。要修剪它,你必须使用上面的压缩for循环来检查第一个目录中每个对象的类型。

这将首先返回所有类型为“type”的对象,这几乎是所有用户定义的类。

答案 1 :(得分:0)

所有django-Models都是models.Model的子类,它有一个元类,用于收集所有模型子类。 通常,不可能获得所有“用户定义的”类。