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

1

3 Answers 3

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')
Sign up to request clarification or add additional context in comments.

2 Comments

Since this uses getattr, i could use this for a function object also right?
For a quick note, to get an instance of the class it would need to be globals()[x]().
2

Have you heard of the inspect module?

Check out this snippet I found.

1 Comment

-1: OP wants to get a class by name, not list all classes names.
-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

1 Comment

Your link and/or example do not answer the question at all.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.