Skip to content

Instantly share code, notes, and snippets.

@ryanwang520
Last active August 29, 2015 14:08
Show Gist options
  • Select an option

  • Save ryanwang520/a0399a2ef950fc50b43a to your computer and use it in GitHub Desktop.

Select an option

Save ryanwang520/a0399a2ef950fc50b43a to your computer and use it in GitHub Desktop.
"""
method和function是一回事,classmethod则是另一个类型,所有对类中方法的调用都是经过了descriptor变换成bounded method对象,最后再访问
类型为<class 'method-wrapper'>的__call__属性
这么看来其实也是classmethod,method,function都是统一到了descriptor对象,
"""
from functools import wraps
class my_classmethod:
def __init__(self, func):
wraps(func)(self)
def __get__(self, instance, owner):
return self.__wrapped__.__get__(owner, owner)
class M:
@my_classmethod
def f(cls):
print(cls)
return cls
@classmethod
def f1(self):
print(self)
return self
print(type(f))
print(type(f1))
def f2(self): pass
global F
global F2
global F1
F = f
F2 = f2
F1 = f1
print(type(f2))
M.f1()
M().f1()
assert M.f2 is F2
assert M.f is not F
assert M().f1 is not F1
assert M.f() is M
assert M().f() is M
assert M().f() == M
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment