Python类相关的装饰器

一、装饰器装饰类方法

from functools import wraps
def wrapper(func):
    @wraps(func)
    def inner(self,*args,**kwargs):
        # 此时的self是Person的实例对象
        self.name += "爱吃糖"
        # func ===>  printInfo
        ret = func(self,*args,**kwargs)
        return ret

    return inner


class Person(object):
    def __init__(self,name):
        self.name = name

    @wrapper
    def printInfo(self):
        print(self.name)

# printInfo ==> wraper(printInfo) ==> inner
Person("张三").printInfo()

# 张三爱吃糖

二、类装饰器实现单例模式

def wrapper(obj):
    def inner(name,*args,**kwrags):
        if not obj.instance:
            obj.instance = obj(name)
        return obj.instance
    return inner

@wrapper
class Person(object):
    instance = None
    def __init__(self,name):
        self.name = name

    def printInfo(self):
        print(self.name)

zs = Person('张三')
zs.printInfo()
print(id(zs))

ls = Person('李四')
ls.printInfo()
print(id(ls))

三、给装饰器写log

import time
from functools import wraps

def log(func):
    @wraps(func)
    def inner(fun,*args,**kwargs):
        print("%s执行了"%(func))
        ret = func(fun)
        return ret
    return inner

@log
def wraper(func):
    @wraps(func)
    def inner(*args,**kwargs):
        start_time = time.time()
        ret = func()
        endtime = time.time() - start_time
        print(endtime)
        return ret
    return inner

@wraper
def func():
    time.sleep(5)
    print("func执行了")

# wraper(func) ==>log(wraper) ==>inner
# func() ==> wraper(func)==>inner
func()

 

posted @ 2018-07-27 20:52  短毛兔  阅读(3814)  评论(0编辑  收藏  举报