PythonPython

2、装饰器decorator

2019-04-28  本文已影响18人  代码充电宝
(1)装饰器概述
# 期望函数在被调用时打印log
def f1(x):
    return x*2
def f2(x):
    return x*x
def f3(x):
    return x*x*x
# 装饰器函数 接受函数作为参数,进行包装后,返回一个新的函数
def new_fn(f):
    def fn(x):
        print 'call','()'
        return f(x)
    return fn
# 调用装饰器函数 方式一
g1 = new_fn(f1)
print g1(5)
# 调用装饰器函数 方式二
# f1函数的原始函数被彻底隐藏了
f1 = new_fn(f1)
print f1(5)
(2)log装饰器
#定义@log
#*args, **kw可以让任意参数的函数都适应
def log(f):
    def fn(*args, **kw):
        print('call ' +f.__name__+'()...')
        return f(*args, **kw)
    return fn
@log
def fact(n):
    return n*2
# call fact()...
# 8
print(fact(4))
@log
def add(x, y):
    return x + y
# call add()...
# 3
print(add(1, 2))
(3)performance装饰器
import time
def performance(f):
    def fn(*args,**kw):
        t1 = time.time()
        r = f(*args,**kw)
        t2 = time.time()
        print('call %s() in %fs' % (f.__name__, (t2 - t1)))
        return r
    return fn
@performance
def factorial(n):
    return n*3
print(factorial(10))
# <function performance at 0x10f8edb90>
print(performance)
# <function fn at 0x10f8f1d70>
print(performance(factorial))
(4)set/get封装
class Student(object):
    def __init__(self, name, score):
        self.name = name
        self.__score = score
    @property
    def score(self):
        return self.__score
    @score.setter
    def score(self,score):
        if score < 0 or score > 100:
            raise ValueError('invalid score')
        self.__score = score
s = Student('Bob',59)
print(s.score)
# raise ValueError('invalid score')
# s.score = -10
上一篇下一篇

猜你喜欢

热点阅读