【发布时间】:2013-02-21 05:28:10
【问题描述】:
例如我有一个基类如下:
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')
有没有一种不错的 Pythonic 方法可以通过将新类放入我当前范围的函数调用动态创建这些类,例如:
foo(BaseClass, "My")
a = MyClass()
...
因为会有 cmets 和我为什么需要这个问题:派生类都具有完全相同的内部结构,但不同之处在于构造函数采用了许多以前未定义的参数。因此,例如,MyClass 采用关键字 a,而类 TestClass 的构造函数采用 b 和 c。
inst1 = MyClass(a=4)
inst2 = MyClass(a=5)
inst3 = TestClass(b=False, c = "test")
但他们不应该使用类的类型作为输入参数,比如
inst1 = BaseClass(classtype = "My", a=4)
我得到了这个工作,但更喜欢另一种方式,即动态创建的类对象。
【问题讨论】:
-
只是为了确定,您希望实例的类型根据提供的参数而改变?就像我给
a一样,它总是MyClass而TestClass永远不会接受a?为什么不在BaseClass.__init__()中声明所有3 个参数,而是将它们全部默认为None?def __init__(self, a=None, b=None, C=None)? -
我不能在基类中声明任何东西,因为我不知道我可能使用的所有参数。我可能有 30 个不同的类,每个类有 5 个不同的参数,因此在构造函数中声明 150 个参数不是解决方案。
标签: python class inheritance