Python: Class factory using user input as class names

后端 未结 2 1716
清酒与你
清酒与你 2021-02-03 10:41

I want to add class atttributes to a superclass dynamically. Furthermore, I want to create classes that inherit from this superclass dynamically, and the name of those subclasse

2条回答
  •  难免孤独
    2021-02-03 11:20

    Have a look at the type() builtin function.

    knight_class = type('Knight', (Unit,), {})
    
    • First parameter: Name of new class
    • Second parameter: Tuple of parent classes
    • Third parameter: dictionary of class attributes.

    But in your case, if the subclasses don't implement a different behaviour, maybe giving the Unit class a name attribute is sufficient.

提交回复
热议问题