例如,我有一个如下的基类:
class BaseClass(object):
def __init__(self, classtype):
self._type = classtype
我从这个类派生出其他几个类,例如。
class TestClass(BaseClass):
def __init__(self):
super(TestClass, self).__init__('Test')
class SpecialClass(BaseClass):
def __init__(self):
super(TestClass, self).__init__('Special')
Is there a nice, pythonic way to create those classes dynamically by a function call that puts the new class into my current scope, like:
foo(BaseClass, "My")
a = MyClass()
...
由于会有注释和问题,我为什么需要这样做: 派生类都具有完全相同的内部结构,只是存在差异,即构造函数接受许多以前未定义的参数。例如,MyClass
接受关键字 a
,而类 TestClass
的构造函数接受 b
和 c
。
inst1 = MyClass(a=4)
inst2 = MyClass(a=5)
inst3 = TestClass(b=False, c = "test")
But they should NEVER use the type of the class as input argument like
inst1 = BaseClass(classtype = "My", a=4)
我得到了这个工作,但更喜欢其他方式,即动态创建的类对象。