Skip to content

Instantly share code, notes, and snippets.

@methane
Created February 8, 2012 13:36
Show Gist options
  • Select an option

  • Save methane/1769526 to your computer and use it in GitHub Desktop.

Select an option

Save methane/1769526 to your computer and use it in GitHub Desktop.
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>
@methane
Copy link
Copy Markdown
Author

methane commented Feb 8, 2012

f は C.m を c に束縛 (bound) したメソッドオブジェクト。 c.m() は type(c).m(c) のシンタックスシュガーではなく、 f=c.m; f(); を1行に書いているだけ。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment