装饰器函数

装饰器函数

什么是装饰器函数?

  装饰器函数的本质就是闭包函数,也就是函数嵌套,内部函数调用外层函数变量

装饰器函数的功能

  在不修改原函数以及调用方式的情况下,对原函数的功能进行扩展.

def warpper(func):
    def inner():
        ret = func()
        return ret
    return inner

@warpper  #这里func1 = warpper(func1)  也就是inner()
def func1()
    print('is ok!')
func1()

#被装饰器修饰过的函数在执行的步骤:
    1.执行func1()的时候先执行warpper函数,同时将下面func1函数作为参数赋值func1()
    2.这时warpper函数走完返回inner,inner=赋值后func1
    3.func1() ==inner()调用内存函数
    4.这时候走内存inner函数,内部调用下面func1()打印出 is ok
简单的装饰器函数

为什么要有装饰器函数?

  因为我们在日常开发的过程中,不可能一次性将所有的应用功能全部实现,就算实现了以后也肯定会修改,所以我们必须允许代码可扩展,添加新功能,而装饰器函数恰好能够解决这一问题.在这种背景下,装饰器函数应用能够极大提高开发效率.

继续探索带参数的装饰器函数

import time

def timer(func):

    def inner(num):
        start = time.time()
        func(num)
        print(time.time()-start)
    return inner

@timer
def func(num):
    print(num)

func(1010)

#输出 : 1010
            0.0
简单的带参数的装饰器函数

通过查看上面代码发现装饰器函数没有返回值,没有返回值的函数可是缺乏灵魂的呢!

带参数有返回值的装饰器函数

#一个装饰器装饰多个函数
def warpper(func):
def inner(*args,**kwargs):
print('nice')
ret = func(*args,**kwargs)
print('bad')
return ret
return inner

@warpper
def func(*args,**kwargs):
print('The python is perfect!')
@warpper
def func1(*args,**kwargs):
print('The js is good!')

func()
func1()
#输出:

  nice
  The python is perfect!
  bad
  nice
  The js is good!
  bad

 假如很多函数使用了一个装饰器,想要取消部分装饰器怎么办呢?

def outer(flag):
    def timer(func):
        def inner(*args,**kwargs):
            ret = func(*args, **kwargs)
            if flag:
                print(time.time())
            return ret
        return inner
    return timer
@outer(True)
def func():
    print('linux')
func()

#给装饰器再添加异常flag判断,当装饰器为False快速取消装饰器
取消装饰器效果

 

多个装饰器装饰一个函数的效果

def warpper1(func):
    def inner(*args,**kwargs):
        print('w1情不知所起')
        ret = func(*args,**kwargs)
        print('w1一往而情深')
        return ret
    return inner
def warpper2(func):
    def inner(*args,**kwargs):
        print('w2情不知所起')
        ret = func(*args,**kwargs)
        print('w2一往而情深')
        return ret
    return inner

@warpper1   #  func = warpper1(warpper2.inner) 此时的func是被warpper1.inner
@warpper2   #  func = warpper2(func) 此时的func是warpper2.inner
def func():
    print('You can you up!')
func()
#输出结果
    w1情不知所起
    w2情不知所起
    You can you up!
    w2一往而情深
    w1一往而情深

#执行步骤: 1.首先走wapper1.inner  因此首先打印'w1情不知所起',
         2.往下执行,遇到ret = func()执行调用,此时调用的其实是warpper2.inner,因此跳转到warpper2的inner,打印出'w2情不知所起',
         3.继续往下执行,再次遇到 ret = func().执行调用,此时调用的是原先的func函数,因此打印'You can you up!',
         4.往下执行,打印'w2一往而情深',
         5.由于warpper1函数并没有走完,因此回去再次往下执行,打印'w1一往而情深'.
多个装饰器装饰一个函数

 

装饰器的修复技术

示例1
from functools import wraps

def ww(func):
    #@wraps(func)
    def inner(*args,**kwargs):
        ret = func(*args,**kwargs)
        return ret
    return inner

@ww
def func():
    '''
    你好
    :return:
    '''
    pass
func()
print(func.__name__)
print(func.__doc__)

#输出结果
    inner
    None   
对比示例2 来看更加清晰
示例2
from functools import wraps

def ww(func):
    @wraps(func)
    def inner(*args,**kwargs):
        ret = func(*args,**kwargs)
        return ret
    return inner

@ww
def func():
    '''
    你好
    :return:
    '''
    pass
func()
print(func.__name__)
print(func.__doc__)
#输出
func

    你好
    :return:
#由此看到添加@warps(func)后 被装饰过的func函数名称再调用的时候就是func了,也可以看到 func函数的注释等
装饰器的修复技术

 

 总结:巧妙的运用装饰器函数是非常重要的

...

 

posted @ 2019-01-22 21:47  FindSoul  阅读(198)  评论(0编辑  收藏  举报
var RENDERER = { POINT_INTERVAL : 5, FISH_COUNT : 3, MAX_INTERVAL_COUNT : 50, INIT_HEIGHT_RATE : 0.5, THRESHOLD : 50, init : function(){ this.setParameters(); this.reconstructMethods(); this.setup(); this.bindEvent(); this.render(); }, setParameters : function(){ this.$window = $(window); this.$container = $('#jsi-flying-fish-container'); this.$canvas = $('
'); this.context = this.$canvas.appendTo(this.$container).get(0).getContext('2d-disabled'); this.points = []; this.fishes = []; this.watchIds = []; }, createSurfacePoints : function(){ var count = Math.round(this.width / this.POINT_INTERVAL); this.pointInterval = this.width / (count - 1); this.points.push(new SURFACE_POINT(this, 0)); for(var i = 1; i < count; i++){ var point = new SURFACE_POINT(this, i * this.pointInterval), previous = this.points[i - 1]; point.setPreviousPoint(previous); previous.setNextPoint(point); this.points.push(point); } }, reconstructMethods : function(){ this.watchWindowSize = this.watchWindowSize.bind(this); this.jdugeToStopResize = this.jdugeToStopResize.bind(this); this.startEpicenter = this.startEpicenter.bind(this); this.moveEpicenter = this.moveEpicenter.bind(this); this.reverseVertical = this.reverseVertical.bind(this); this.render = this.render.bind(this); }, setup : function(){ this.points.length = 0; this.fishes.length = 0; this.watchIds.length = 0; this.intervalCount = this.MAX_INTERVAL_COUNT; this.width = this.$container.width(); this.height = this.$container.height(); this.fishCount = this.FISH_COUNT * this.width / 500 * this.height / 500; this.$canvas.attr({width : this.width, height : this.height}); this.reverse = false; this.fishes.push(new FISH(this)); this.createSurfacePoints(); }, watchWindowSize : function(){ this.clearTimer(); this.tmpWidth = this.$window.width(); this.tmpHeight = this.$window.height(); this.watchIds.push(setTimeout(this.jdugeToStopResize, this.WATCH_INTERVAL)); }, clearTimer : function(){ while(this.watchIds.length > 0){ clearTimeout(this.watchIds.pop()); } }, jdugeToStopResize : function(){ var width = this.$window.width(), height = this.$window.height(), stopped = (width == this.tmpWidth && height == this.tmpHeight); this.tmpWidth = width; this.tmpHeight = height; if(stopped){ this.setup(); } }, bindEvent : function(){ this.$window.on('resize', this.watchWindowSize); this.$container.on('mouseenter', this.startEpicenter); this.$container.on('mousemove', this.moveEpicenter); this.$container.on('click', this.reverseVertical); }, getAxis : function(event){ var offset = this.$container.offset(); return { x : event.clientX - offset.left + this.$window.scrollLeft(), y : event.clientY - offset.top + this.$window.scrollTop() }; }, startEpicenter : function(event){ this.axis = this.getAxis(event); }, moveEpicenter : function(event){ var axis = this.getAxis(event); if(!this.axis){ this.axis = axis; } this.generateEpicenter(axis.x, axis.y, axis.y - this.axis.y); this.axis = axis; }, generateEpicenter : function(x, y, velocity){ if(y < this.height / 2 - this.THRESHOLD || y > this.height / 2 + this.THRESHOLD){ return; } var index = Math.round(x / this.pointInterval); if(index < 0 || index >= this.points.length){ return; } this.points[index].interfere(y, velocity); }, reverseVertical : function(){ this.reverse = !this.reverse; for(var i = 0, count = this.fishes.length; i < count; i++){ this.fishes[i].reverseVertical(); } }, controlStatus : function(){ for(var i = 0, count = this.points.length; i < count; i++){ this.points[i].updateSelf(); } for(var i = 0, count = this.points.length; i < count; i++){ this.points[i].updateNeighbors(); } if(this.fishes.length < this.fishCount){ if(--this.intervalCount == 0){ this.intervalCount = this.MAX_INTERVAL_COUNT; this.fishes.push(new FISH(this)); } } }, render : function(){ requestAnimationFrame(this.render); this.controlStatus(); this.context.clearRect(0, 0, this.width, this.height); this.context.fillStyle = 'hsl(0, 0%, 95%)'; for(var i = 0, count = this.fishes.length; i < count; i++){ this.fishes[i].render(this.context); } this.context.save(); this.context.globalCompositeOperation = 'xor'; this.context.beginPath(); this.context.moveTo(0, this.reverse ? 0 : this.height); for(var i = 0, count = this.points.length; i < count; i++){ this.points[i].render(this.context); } this.context.lineTo(this.width, this.reverse ? 0 : this.height); this.context.closePath(); this.context.fill(); this.context.restore(); } }; var SURFACE_POINT = function(renderer, x){ this.renderer = renderer; this.x = x; this.init(); }; SURFACE_POINT.prototype = { SPRING_CONSTANT : 0.03, SPRING_FRICTION : 0.9, WAVE_SPREAD : 0.3, ACCELARATION_RATE : 0.01, init : function(){ this.initHeight = this.renderer.height * this.renderer.INIT_HEIGHT_RATE; this.height = this.initHeight; this.fy = 0; this.force = {previous : 0, next : 0}; }, setPreviousPoint : function(previous){ this.previous = previous; }, setNextPoint : function(next){ this.next = next; }, interfere : function(y, velocity){ this.fy = this.renderer.height * this.ACCELARATION_RATE * ((this.renderer.height - this.height - y) >= 0 ? -1 : 1) * Math.abs(velocity); }, updateSelf : function(){ this.fy += this.SPRING_CONSTANT * (this.initHeight - this.height); this.fy *= this.SPRING_FRICTION; this.height += this.fy; }, updateNeighbors : function(){ if(this.previous){ this.force.previous = this.WAVE_SPREAD * (this.height - this.previous.height); } if(this.next){ this.force.next = this.WAVE_SPREAD * (this.height - this.next.height); } }, render : function(context){ if(this.previous){ this.previous.height += this.force.previous; this.previous.fy += this.force.previous; } if(this.next){ this.next.height += this.force.next; this.next.fy += this.force.next; } context.lineTo(this.x, this.renderer.height - this.height); } }; var FISH = function(renderer){ this.renderer = renderer; this.init(); }; FISH.prototype = { GRAVITY : 0.4, init : function(){ this.direction = Math.random() < 0.5; this.x = this.direction ? (this.renderer.width + this.renderer.THRESHOLD) : -this.renderer.THRESHOLD; this.previousY = this.y; this.vx = this.getRandomValue(4, 10) * (this.direction ? -1 : 1); if(this.renderer.reverse){ this.y = this.getRandomValue(this.renderer.height * 1 / 10, this.renderer.height * 4 / 10); this.vy = this.getRandomValue(2, 5); this.ay = this.getRandomValue(0.05, 0.2); }else{ this.y = this.getRandomValue(this.renderer.height * 6 / 10, this.renderer.height * 9 / 10); this.vy = this.getRandomValue(-5, -2); this.ay = this.getRandomValue(-0.2, -0.05); } this.isOut = false; this.theta = 0; this.phi = 0; }, getRandomValue : function(min, max){ return min + (max - min) * Math.random(); }, reverseVertical : function(){ this.isOut = !this.isOut; this.ay *= -1; }, controlStatus : function(context){ this.previousY = this.y; this.x += this.vx; this.y += this.vy; this.vy += this.ay; if(this.renderer.reverse){ if(this.y > this.renderer.height * this.renderer.INIT_HEIGHT_RATE){ this.vy -= this.GRAVITY; this.isOut = true; }else{ if(this.isOut){ this.ay = this.getRandomValue(0.05, 0.2); } this.isOut = false; } }else{ if(this.y < this.renderer.height * this.renderer.INIT_HEIGHT_RATE){ this.vy += this.GRAVITY; this.isOut = true; }else{ if(this.isOut){ this.ay = this.getRandomValue(-0.2, -0.05); } this.isOut = false; } } if(!this.isOut){ this.theta += Math.PI / 20; this.theta %= Math.PI * 2; this.phi += Math.PI / 30; this.phi %= Math.PI * 2; } this.renderer.generateEpicenter(this.x + (this.direction ? -1 : 1) * this.renderer.THRESHOLD, this.y, this.y - this.previousY); if(this.vx > 0 && this.x > this.renderer.width + this.renderer.THRESHOLD || this.vx < 0 && this.x < -this.renderer.THRESHOLD){ this.init(); } }, render : function(context){ context.save(); context.translate(this.x, this.y); context.rotate(Math.PI + Math.atan2(this.vy, this.vx)); context.scale(1, this.direction ? 1 : -1); context.beginPath(); context.moveTo(-30, 0); context.bezierCurveTo(-20, 15, 15, 10, 40, 0); context.bezierCurveTo(15, -10, -20, -15, -30, 0); context.fill(); context.save(); context.translate(40, 0); context.scale(0.9 + 0.2 * Math.sin(this.theta), 1); context.beginPath(); context.moveTo(0, 0); context.quadraticCurveTo(5, 10, 20, 8); context.quadraticCurveTo(12, 5, 10, 0); context.quadraticCurveTo(12, -5, 20, -8); context.quadraticCurveTo(5, -10, 0, 0); context.fill(); context.restore(); context.save(); context.translate(-3, 0); context.rotate((Math.PI / 3 + Math.PI / 10 * Math.sin(this.phi)) * (this.renderer.reverse ? -1 : 1)); context.beginPath(); if(this.renderer.reverse){ context.moveTo(5, 0); context.bezierCurveTo(10, 10, 10, 30, 0, 40); context.bezierCurveTo(-12, 25, -8, 10, 0, 0); }else{ context.moveTo(-5, 0); context.bezierCurveTo(-10, -10, -10, -30, 0, -40); context.bezierCurveTo(12, -25, 8, -10, 0, 0); } context.closePath(); context.fill(); context.restore(); context.restore(); this.controlStatus(context); } }; $(function(){ RENDERER.init(); });