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/537a2470b2c8db3f284d to your computer and use it in GitHub Desktop.

Select an option

Save ryanwang520/537a2470b2c8db3f284d to your computer and use it in GitHub Desktop.
"""
同时修饰classmethod,bound_method, function的decorator
"""
from functools import wraps
import types
class Profile:
def __init__(self, func):
wraps(func)(self)
self.func_calls = 0
def _profile_work(self):
self.func_calls += 1
print('func calls', self.func_calls)
def __call__(self, *args, **kwargs):
self._profile_work()
return self.__wrapped__(*args, **kwargs)
def __get__(self, instance, owner):
if instance is None:
print(owner)
cm = self.__wrapped__
self._profile_work()
#对象或者类对classmethod或者method取值,得到的是经过他们__get__方法算出的结果,前者是绑定到class对象,后者绑定到调用者本身
#classmethod和普通的function或者method都是descriptor对象,只不过__get__的时候会丢掉第一个参数(instance)
return cm.__get__(None, owner)
return types.MethodType(self, instance)
class Math:
@Profile
@classmethod
def add(cls, a, b):
return a + b
@Profile
def multi(self, a, b):
return a * b
@Profile
def minus(a, b):
return a - b
# print(Math().add(2, 3))
# print(Math().add(2, 3))
# print(Math().add(2, 3))
print(Math.add(2, 3))
print(Math.add(2, 3))
print(Math.add(2, 3))
math = Math()
math.multi(1, 2)
math.multi(1, 2)
math.multi(1, 2)
minus(2, 1)
minus(2, 1)
minus(2, 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment