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?
In Python,
The first line makes the variable
classNamerefer to the same thing asMyClass. Then the next line calls theMyClassconstructor through theclassNamevariable.As a concrete example:
(In Python,
listis the constructor for thelistclass.)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.