通常、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
基本クラスのメソッドを呼び出すときにインスタンスを明示的に渡す必要があるのはなぜですか?