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

空扰寡人 提交于 2019-12-04 17:14:16

问题


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 A, with only one addition: a certain class attribute is added and is set to equal x.

In other words:

class C(A):
  C.p = x # x is the parameter passed to the factory function

Is this easy to do? Are there any issues I should be aware of?


回答1:


First off, note that the term "class factory" is somewhat obsolete in Python. It's used in languages like C++, for a function that returns a dynamically-typed instance of a class. It has a name because it stands out in C++; it's not rare, but it's uncommon enough that it's useful to give the pattern a name. In Python, however, this is done constantly--it's such a basic operation that nobody bothers giving it a special name anymore.

Also, note that a class factory returns instances of a class--not a class itself. (Again, that's because it's from languages like C++, which have no concept of returning a class--only objects.) However, you said you want to return "a new class", not a new instance of a class.

It's trivial to create a local class and return it:

def make_class(x):
    class C(A):
        p = x
    return C



回答2:


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.



来源:https://stackoverflow.com/questions/4858298/python-3-class-template-function-that-returns-a-parameterized-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!