Using Variables for Class Names in Python?

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

    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.

提交回复
热议问题