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();
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.