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

后端 未结 2 1727
谎友^
谎友^ 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:19

    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
    

提交回复
热议问题