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")
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.
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.
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 ( {} ).
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With