python 3: class “template” (function that returns a parameterized class)

后端 未结 2 1723
谎友^
谎友^ 2021-02-12 09:59

I am trying to create a function that is passed a parameter x and returns a new class C. C should be a subclass of a fixed base class

2条回答
  •  庸人自扰
    2021-02-12 10:28

    The type function has a 3-argument version which dynamically constructs a new class. Pass the name, bases and a dict containing the attributes and methods of the class.

    In your case:

    def class_factory(x):
        return type("C", (A,), {"p": x})
    

    You can obviously dynamically set the name of the class, "C", but note that in order to make the class publicly accessible, you also need to assign the result of the function to a variable. You can do that dynamically using globals()["C"] = ..., or assign the classes to a dictionary, whatever.

提交回复
热议问题