Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

class - Python: get only classes defined in imported module with dir()?

I've got a module written in Python. I now want to import it into another script and list all classes I defined in this module. So I try:

>>> import my_module
>>> dir(my_module)
['BooleanField', 'CharField', 'DateTimeField', 'DecimalField', 'MyClass', 'MySecondClass', 'ForeignKeyField', 'HStoreField', 'IntegerField', 'JSONField', 'TextField', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'datetime', 'db', 'division', 'os', 'struct', 'uuid']

The only two classes which I defined in my_module are MyClass and MySecondClass, the other stuff are all things that I imported into my_module.

I now want to somehow be able to get a list of all classes which are defined in my_module without getting all the other stuff. Is there a way to do this in Python?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the inspect module to inspect live objects:

>>> import inspect
>>> import my_module
>>> [m[0] for m in inspect.getmembers(my_module, inspect.isclass) if m[1].__module__ == 'my_module']

That should then work, getting every class defined within that my_module.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...