Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialise class object by name

Tags:

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

like image 220
zsquare Avatar asked Oct 27 '10 07:10

zsquare


People also ask

How do you initialize a class object?

There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator.

How do you initialize an object with an object?

To create an object of a named class by using an object initializer. Begin the declaration as if you planned to use a constructor. Type the keyword With , followed by an initialization list in braces. In the initialization list, include each property that you want to initialize and assign an initial value to it.

How do you initialize a new object?

Objects can be initialized using new Object() , Object. create() , or using the literal notation (initializer notation). An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ( {} ).


Video Answer


1 Answers

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') 
like image 79
Brian McKenna Avatar answered Oct 10 '22 16:10

Brian McKenna