如何在函数中动态生成子类?

2024-09-19 23:33:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个函数,该函数创建一个新的子类,该子类的名称是作为参数传递的字符串。我不知道什么样的工具最适合这样做,但我在下面的代码中尝试了一下,只设法生成了一个名为“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)

Tags: 工具函数字符串代码self名称initdef
2条回答

最安全、最简单的方法是使用type内置函数。这需要一个可选的第二个参数(基类的元组)和第三个参数(函数的dict)。我的建议如下:

def makeNewClass(x):
    def init(self,attribute1,attribute2):
        # make sure you call the base class constructor here 
        self.attribute2 = attribute2

    # make a new type and return it
    return type(x, (MySuperClass,), {'__init__': init})

x = "MySubClass"
MySubClass = makeNewClass(x)

您将需要在第三个参数的dict中填充您希望新类拥有的所有内容。很可能您正在生成类,并希望将它们推回到一个列表中,在列表中名称实际上并不重要。我不知道你的用例。在


{或者,您可以将 ^{pr2}$

Ryan的答案是完整的,但我认为值得注意的是,除了使用内置的typeexec/eval或其他方法之外,至少还有一种邪恶的方法可以做到这一点:

class X:
    attr1 = 'some attribute'

    def __init__(self):
        print 'within constructor'

    def another_method(self):
        print 'hey, im another method'

# black magics
X.__name__ = 'Y'
locals()['Y'] = X
del X

# using our class
y = locals()['Y']()
print y.attr1
y.another_method()

注意,我只在创建类Y和初始化{}的实例时使用字符串,所以这个方法是完全动态的。在

相关问题 更多 >