24

Since everything in python is an object, i was wondering if there was a way i could initialise a class object using the name of the class

for example,

class Foo:
    """Class Foo"""

How could i access this class by "Foo", ie something like c = get_class("Foo")

zsquare
  • 9,916
  • 6
  • 53
  • 87
  • 1
    possible duplicate of [Does python have an equivalent to Java Class.forName()?](http://stackoverflow.com/questions/452969/does-python-have-an-equivalent-to-java-class-forname) – mikej Oct 27 '10 at 07:57

3 Answers3

45

If the class is in your scope:

get_class = lambda x: globals()[x]

If you need to get a class from a module, you can use getattr:

import urllib2
handlerClass = getattr(urllib2, 'HTTPHandler')
Brian McKenna
  • 45,528
  • 6
  • 61
  • 60
2

Have you heard of the inspect module?

Check out this snippet I found.

Michael Mior
  • 28,107
  • 9
  • 89
  • 113
jknair
  • 4,709
  • 1
  • 17
  • 20
-2

I think your searching reflection see http://en.wikipedia.org/wiki/Reflection_%28computer_science%29#Python

Or a better Example from the german wikipedia:

>>> # the object
>>> class Person(object):
...    def __init__(self, name):
...        self.name = name
...    def say_hello(self):
...        return 'Hallo %s!' % self.name
...
>>> ute = Person('Ute')
>>> # direct
>>> print ute.say_hello()
Hallo Ute!
>>> # Reflexion
>>> m = getattr(ute, 'say_hello')()
>>> # (equals ute.say_hello())
>>> print m
Hallo Ute!

from http://de.wikipedia.org/wiki/Reflexion_%28Programmierung%29#Beispiel_in_Python

Michael Mior
  • 28,107
  • 9
  • 89
  • 113
kasten
  • 602
  • 2
  • 6
  • 17