Created
February 8, 2012 13:36
-
-
Save methane/1769526 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| In [1]: class C(object): | |
| ...: def m(self): | |
| ...: pass | |
| ...: | |
| In [2]: c=C() | |
| In [3]: f=c.m | |
| In [4]: f() | |
| In [5]: f | |
| Out[5]: <bound method C.m of <__main__.C object at 0x1e10d10>> | |
| # インスタンスを this というキーワード引数で渡すようなメソッドを作ってみる。 | |
| In [8]: class MyMethod(object): | |
| ...: def __init__(self, func): | |
| ...: self._f = func | |
| ...: def __get__(self, obj, klass=None): | |
| ...: def func(*args, **kw): | |
| ...: return self._f(*args, this=obj, **kw) | |
| ...: return func | |
| ...: | |
| In [9]: class D(object): | |
| ...: @MyMethod | |
| ...: def f(a,b,this): | |
| ...: print a,b,this | |
| ...: | |
| In [10]: d=D() | |
| In [11]: d.f(1,2) | |
| 1 2 <__main__.D object at 0x1e33110> |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
f は C.m を c に束縛 (bound) したメソッドオブジェクト。 c.m() は type(c).m(c) のシンタックスシュガーではなく、 f=c.m; f(); を1行に書いているだけ。