tags:

views:

44

answers:

3

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")

+2  A: 

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
Since this uses getattr, i could use this for a function object also right?
zsquare
Yep, `getattr(urllib2, 'urlopen')` works as expected
Brian McKenna
A: 

I think your searching reflexion 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

kasten
+1  A: 

have u heard of the inspect module : http://docs.python.org/library/inspect.html

chk out a snippet i found : http://code.activestate.com/recipes/553262-list-classes-methods-and-functions-in-a-module/

jknair