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"TypeErrorstrintcls('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 に答える