我正在尝试编写一个函数,该函数创建一个新的子类,该子类的名称是作为参数传递的字符串。我不知道什么样的工具最适合这样做,但我在下面的代码中尝试了一下,只设法生成了一个名为“x”的子类,而不是像预期的那样“MySubClass”。如何才能正确编写此函数?在
class MySuperClass:
def __init__(self,attribute1):
self.attribute1 = attribute1
def makeNewClass(x):
class x(MySuperClass):
def __init__(self,attribute1,attribute2):
self.attribute2 = attribute2
x = "MySubClass"
makeNewClass(x)
myInstance = MySubClass(1,2)
最安全、最简单的方法是使用
type
内置函数。这需要一个可选的第二个参数(基类的元组)和第三个参数(函数的dict)。我的建议如下:您将需要在第三个参数的dict中填充您希望新类拥有的所有内容。很可能您正在生成类,并希望将它们推回到一个列表中,在列表中名称实际上并不重要。我不知道你的用例。在
{或者,您可以将
^{pr2}$
Ryan的答案是完整的,但我认为值得注意的是,除了使用内置的
type
和exec
/eval
或其他方法之外,至少还有一种邪恶的方法可以做到这一点:注意,我只在创建类}的实例时使用字符串,所以这个方法是完全动态的。在
Y
和初始化{相关问题 更多 >
编程相关推荐