Pixel Pedals of Tomakomai

北海道苫小牧市出身の初老の日常

メソッドはインスタンスにboundされる

メソッドと関数は違うものっぽいです。

>>> class MyClass(object):
...     def print_hello(self=None): print "hello! just say Hello!"
... 
>>> MyClass.print_hello()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method print_hello() must be called with MyClass instance as first argument (got nothing instead)


MyClassのprint_helloって属性に関数オブジェクトが入ってるのかと思ったら、そうでもない模様です。インスタンスがないと呼べないって怒られてます。


で、色々ググってたら、ユーザ定義メソッド (user-defined method)の解説に辿り着きました。

ユーザ定義のメソッドオブジェクトは、クラスやクラスインスタンス (あるいは None) を任意の呼び出し可能オブジェクト (通常は ユーザ定義関数) と結合し (combine) ます。

読み出し専用の特殊属性: im_self は クラスインスタンスオブジェクトで、im_func は関数オブジェクト です; im_class は結合メソッド (bound method) において im_self が属しているクラスか、あるいは非結合メソッド (unbound method) において、要求されたメソッドを定義している クラスです;


combine って言うのか。どうやらim_funcに、元の関数が居るようです。

>>> MyClass.print_hello.im_func()
hello! just say Hello!


呼べた! なるほど、面白いですね。ついでにim_selfとim_classをチェックして今日はお別れです。

>>> MyClass.print_hello.im_self
>>> MyClass.print_hello.im_class
<class '__main__.MyClass'>
>>> MyClass().print_hello.im_self
<__main__.MyClass object at 0x560750>
>>> MyClass().print_hello.im_class
<class '__main__.MyClass'>