1

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

必须有某种方法可以从按类型创建的子类中调用超类方法,但是如果我能看到怎么做,我会感到震惊。

4

2 回答 2

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)
于 2013-03-20T06:04:10.723 回答
1

这似乎有效,可以做你想做的事。self.foo = self.anArg + 3必须更改该语句,self.foo = self.anArg + "3"以避免TypeError在尝试连接 astr和一个对象时避免 a ,如您的问题中的代码所示,调用int会发生这种情况。cls('f00')

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')
    d = {}
    exec(source, d)
    cls = type(name, (VeryImportantSuperClass,), d)
    d[name] = cls
    return cls

if __name__ == '__main__':
    cls = createSubclassAttempt1('Foo')
    inst = cls('foo')
    print(cls('foo').foo)  # prints "foo3"

(适用于 Python 2.7.3 和 3.3)

于 2013-03-20T08:17:16.950 回答