python 3:类“模板” (返回参数化类的函数) [英] python 3: class "template" (function that returns a parameterized class)
问题描述
我试图创建一个传递参数 x
并返回新类 C
的函数。 C
应该是固定基类 A
的子类,仅添加一个:添加特定的类属性,然后设置为等于 x
。
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
.
换句话说:
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?
推荐答案
首先,请注意,类工厂一词在某些情况下已过时蟒蛇。它用于C ++之类的语言中,用于返回动态类型的类实例的函数。它之所以命名,是因为它在C ++中脱颖而出。虽然这种情况并不罕见,但是它并不常见,因此给模式命名很有用。但是,在Python中,这是不断进行的操作-这是一项基本操作,没有人再为它起一个特殊的名字。
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.
此外,请注意,类工厂返回实例一个类-不是类本身。 (同样,这是因为它来自C ++之类的语言,它们没有返回类的概念,而只是返回对象。)但是,您说过要返回新类,而不是类的新实例。
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
这篇关于python 3:类“模板” (返回参数化类的函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!