Using Variables for Class Names in Python?

后端 未结 5 461
遥遥无期
遥遥无期 2021-01-30 20:56

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


        
5条回答
  •  醉酒成梦
    2021-01-30 21:40

    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.

提交回复
热议问题