views:

2339

answers:

6

I want to know how to use variables for objects and function names in Python. In PHP, you can do this:

$className = "MyClass";

$newObject = new $className();

How do you do this sort of thing in Python? Or, am I totally not appreciating some fundamental difference with Python, and if so, what is it?

+16  A: 

In Python,

className = MyClass
newObject = className()

The first line makes the variable className refer to the same thing as MyClass. Then the next line calls the MyClass constructor through the className variable.

As a concrete example:

>>> className = list
>>> newObject = className()
>>> newObject
[]

(In Python, list is the constructor for the list class.)

The difference is that in PHP, you represent the name of the class you want to refer to as a string, while in Python you can reference the same class directly. If you must use a string (for example if the name of the class is created dynamically), then you will need to use other techniques.

Greg Hewgill
+1  A: 

Oh, at first I started explaining that you could not do variable name substitution in Python. Which is true, but not really the question asked.

It seems you are indeed missing one fundamental aspect of Python: class, functions and methods are first class values. They can be assigned to variables and used indifferently from within a variable.

ddaa
+1  A: 

If you have this:

class MyClass:
    def __init__(self):
        print "MyClass"

Then you usually do this:

>>> x = MyClass()
MyClass

But you could also do this, which is what I think you're asking:

>>> a = "MyClass"
>>> y = eval(a)()
MyClass

But, be very careful about where you get the string that you use "eval()" on -- if it's come from the user, you're essentially creating an enormous security hole.

TimB
OMG, no! The eval function is evil. Do not use it.
ddaa
I'd say that's a pretty good rule of thumb.
Robert Rossney
+11  A: 

Assuming that some_module has a class named "class_name":

import some_module
klass = getattr(some_module, "class_name")
some_object = klass()

I should note that you should be careful here: turning strings into code can be dangerous if the string came from the user, so you should keep security in mind in this situation. :)

One other method (assuming that we still are using "class_name"):

class_lookup = { 'class_name' : class_name }
some_object = class_lookup['class_name']()  #call the object once we've pulled it out of the dict

The latter method is probably the most secure way of doing this, so it's probably what you should use if at all possible.

Jason Baker
A: 

Without knowing PHP, it's hard to know what you're really trying to do here. Are you trying to create a new class named MyClass at runtime? I don't think there's any reasonable way to do that in Python without using some black magic.

To actually define a class in Python, you would generally just use the class statement:

class MyClass( object ): pass

And you instantiate objects like this:

MyObject = MyClass()
kurosch
If you do not understand the question, do not answer!
desolat
+1  A: 

If you need to create a dynamic class in Python (i.e. one whose name is a variable) you can use type() which takes 3 params: name, bases, attrs

>>> class_name = 'MyClass'
>>> klass = type(class_name, (object,), {'msg': 'foobarbaz'})

<class '__main__.MyClass'>

>>> inst = klass()
>>> inst.msg
foobarbaz
coleifer