美文网首页PythonPython
2、装饰器decorator

2、装饰器decorator

作者: 代码充电宝 | 来源:发表于2019-04-28 08:43 被阅读18次
(1)装饰器概述
  • 在运行时动态增加功能,但不改动函数本身代码
  • Python的 decorator 本质上就是一个高阶函数,它接收一个函数作为参数,然后,返回一个新函数
  • 使用 decorator 用Python提供的@语法,这样可以避免手动编写 f = decorate(f) 这样的代码
  • 不带参数的装饰器
# 期望函数在被调用时打印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:打印日志
#定义@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装饰器
  • 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封装
  • 第一个score(self)是get方法,用@property装饰,
  • 第二个score(self, score)是set方法,用@score.setter装饰,
  • @score.setter是前一个@property装饰后的副产品。
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

相关文章

网友评论

    本文标题:2、装饰器decorator

    本文链接:https://www.haomeiwen.com/subject/fanxnqtx.html