0

通常、Python の基本クラス メソッドは、派生クラスの関数を呼び出すのと同じ方法で、派生クラスから呼び出すことができます。

class Base:
    def base_method(self):
        print("Base method")

class Foo(Base):
    def __init__(self):
        pass

f = Foo()
f.base_method()

ただし、関数を使用してクラスを動的に作成すると、インスタンスtypeを渡さずに基本クラスのメソッドを呼び出すことができません。self

class Base:
    def base_method(self):
        print("Base method")

f = type("Foo", (Base, object), { "abc" : "def" })
f.base_method() # Fails

これは TypeError を発生させます:TypeError: base_method() takes exactly 1 argument (0 given)

明示的にselfパラメーターを渡すと機能します。

f.base_method(f)

self基本クラスのメソッドを呼び出すときにインスタンスを明示的に渡す必要があるのはなぜですか?

4

2 に答える 2

4

あなたの行f = type(...)はインスタンスではなくクラスを返します。

そうすればf().base_method()、うまくいくはずです。

于 2012-09-12T19:09:35.357 に答える
2

typeインスタンスではなくクラスを返します。を呼び出す前に、クラスをインスタンス化する必要がありますbase_method

>>> class Base(object):
...     def base_method(self): print 'a'
... 
>>> f = type('Foo', (Base,), {'arg': 'abc'})
>>> f.base_method()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method base_method() must be called with Foo instance as first argument (got nothing instead)
>>> f().base_method()
a
于 2012-09-12T19:10:02.347 に答える