在由类型创建的子类中调用super

时间:2013-03-20 03:50:22

标签: python inheritance dynamic-class-creation

更新:取得了一些进展并简化了示例,尽管我目前被最新的错误所困扰。我不知道为什么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)

必须有某种方法从类型创建的子类中调用超类方法,但如果我能看到它,我就会破灭。

2 个答案:

答案 0 :(得分:4)

在创建类的函数中使用__init__的闭包:

class VeryImportantSuperClass(object):
    def __init__(self, anArg, anotherArg):
        self.anArg = anArg

def CreateSubclass(name):
    def sub__init__(self, arg):
        super(klass, self).__init__(arg, 6.02e23)
        self.foo = self.anArg + 3

    klass = type(name, (VeryImportantSuperClass, ),
                 {'__init__': sub__init__})
    return klass


if __name__ == '__main__':
    cls = CreateSubclass('Foo')
    print(cls(3).foo)

答案 1 :(得分:1)

这似乎有用,可以做你想做的事。在尝试连接self.foo = self.anArg + 3self.foo = self.anArg + "3"对象时,必须将TypeError语句更改为str以避免int { {1}}如您问题中的代码所示调用。

cls('f00')

(适用于Python 2.7.3和3.3)