Creating class instance from module and class name

Steven D'Aprano steven at
Tue Oct 6 09:47:28 CEST 2009

On Tue, 06 Oct 2009 00:09:08 -0700, gentlestone wrote:

> one more question - __class__ is the way for getting the classname from
> the class instance -

Not quite. __class__ returns the class object, not the name. Given the 
class object, you ask for __name__ to get the name it was defined as[1]. 
For example:

>>> class MyClass:
...     pass
>>> instance = MyClass()
>>> instance.__class__
<class __main__.MyClass at 0xb7f4465c>
>>> MyClass.__name__
>>> instance.__class__.__name__

> how can I get the module name?

>>> import math
>>> math.__name__

But if possible, you should pass around the actual module and class 
objects rather than just their names. The only time you need to use the 
*names* rather than the actual objects themselves is if you are getting 
the information from a source outside of Python, e.g. user input, or a 
text file, etc.

E.g. suppose you have imported the decimal module, and you want access to 
the Decimal class elsewhere. You can pass the names "decimal" and 
"Decimal" to some function, and use __import__() and getattr() to access 
them. Or you can do this:

>>> def example(mod, cls):
...     print "Module is", mod
...     print "Class is", cls
...     return cls(0)  # or whatever you want to do with it...
>>> example(math, decimal.Decimal)  # pass the objects, not the names
Module is <module 'math' from '/usr/lib/python2.5/lib-dynload/'>
Class is <class 'decimal.Decimal'>

[1] But not necessarily the name it has now.


More information about the Python-list mailing list