Using Variables for Class Names in Python?

后端 未结 5 463
遥遥无期
遥遥无期 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:24

    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.

    Update: Using type() as shown in coleifer's answer is far superior to this solution.

提交回复
热议问题