Using Variables for Class Names in Python?

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

    If you need to create a dynamic class in Python (i.e. one whose name is a variable) you can use type() which takes 3 params: name, bases, attrs

    >>> class_name = 'MyClass'
    >>> klass = type(class_name, (object,), {'msg': 'foobarbaz'})
    
    
    
    >>> inst = klass()
    >>> inst.msg
    foobarbaz
    
    • Note however, that this does not 'instantiate' the object (i.e. does not call constructors etc. It creates a new(!) class with the same name.

提交回复
热议问题