更新:取得了一些进展并简化了示例,尽管我目前被最新的错误难住了。我不知道为什么该super().__init__
方法不受约束。
import types
class VeryImportantSuperClass(object):
def __init__(self, anArg, anotherArg):
self.anArg = anArg
#Extremely clever code here
def createSubclassAttempt1(name):
source = 'def __init__(self, arg):\n' +\
' super(' + name + ', self).__init__(arg, 6.02e23)\n' +\
' self.foo = self.anArg + 3\n'
cls = type(name, (VeryImportantSuperClass,), {})
d = {name: cls}
exec source in d
cls.__init__ = types.MethodType(d['__init__'], cls)
return cls
if __name__ == '__main__':
cls = createSubclassAttempt1('Foo')
cls('foo')
输出:
Traceback (most recent call last):
File "/home/newb/eclipseWorkspace/TestArea/subclassWithType.py", line 27, in <module>
cls('foo')
File "<string>", line 2, in __init__
TypeError: unbound method __init__() must be called with Foo instance as first argument (got str instance instead)
必须有某种方法可以从按类型创建的子类中调用超类方法,但是如果我能看到怎么做,我会感到震惊。