裝飾器

python裝飾器做用

python裝飾器就是用於拓展原來函數功能的一種函數,這個函數的特殊之處在於它的返回值也是一個函數,使用python裝飾器的好處就是在不用更改原函數的代碼前提下給函數增長新的功能

完整的裝飾器:

import time
def timmer(func):
    def deco():
        start_time=time.time()
        func()
        stop_time=time.time()
        print("in the func run  is %s" % (stop_time-start_time))
    return deco

@timmer #test1=timmer(test1)
def test1():
    time.sleep(3)
    print("in the test1")
@timmer #=test2=timmer(test2)
def test2():
    time.sleep(3)
    print("in the test2")
test1()
test2()


C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py
in the test1
in the func run  is 3.0001721382141113
in the test2
in the func run  is 3.00017094612121


本身編寫的完整的裝飾器


# -*- coding:UTF-8 -*-
import time
def timmer(func):
    def deco():
        func()
        print("welcome to beijing")
    return deco

@timmer #test1=timmer(test1)
def test1():
    time.sleep(3)
    print("in the test1")
@timmer #=test2=timmer(test2)
def test2():
    time.sleep(3)
    print("in the test2")
test1()
test2()


ssh://root@192.168.0.75:22/usr/bin/python -u /app/py_code/test3.py
in the test1
welcome to beijing
in the test2
welcome to beijing


傳參數


import time
def timmer(func):
    def deco(name):
        start_time=time.time()
        func(name)
        stop_time=time.time()
        print("in the func run  is %s" % (stop_time-start_time))
    return deco

#@timmer #=test1=timmer(test1)
def test1():
    time.sleep(3)
    #print("in the test1")
@timmer #=test2=timmer(test2)
def test2(name):
    time.sleep(3)
    print("in the test2",name)
test1()
test2("bob")

C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py
in the test2 bob
in the func run  is 3.000170946121216


import time
def timmer(func):
    def deco(arg1,arg2):
        start_time=time.time()
        func(arg1,arg2)
        stop_time=time.time()
        print("in the func run  is %s" % (stop_time-start_time))
    return deco

#@timmer #=test1=timmer(test1)
def test1():
    time.sleep(3)
    #print("in the test1")
@timmer #=test2=timmer(test2)
def test2(name,age):
    time.sleep(3)
    print("in the test2",name,age)
test1()
test2("bob",25)



C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py
in the test2 bob 25
in the func run  is 3.000170946121216



通用型傳遞參數的裝飾器

import time
def timmer(func):
    def deco(*args,**kwargs):
        start_time=time.time()
        func(*args,**kwargs)
        stop_time=time.time()
        print("in the func run  is %s" % (stop_time-start_time))
    return deco

#@timmer #=test1=timmer(test1)
def test1():
    time.sleep(3)
    #print("in the test1")
@timmer #=test2=timmer(test2)
def test2(name,age,high):
    time.sleep(3)
    print("in the test2",name,age,high)
test1()
test2("bob",25,170)


C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py
in the test2 bob 25 170
in the func run  is 3.0001721382141113


https://www.cnblogs.com/cicaday/p/python-decorator.html


基於類實現的裝飾器:

裝飾器要求接受一個callable對象,並返回一個callable對象(不太嚴謹,詳見後文)。那麼用類來實現也是也能夠的。咱們能夠讓類的構造函數__init__()接受一個函數,而後重載__call__()並返回一個函數,也能夠達到裝飾器函數的效果。


class logging(object):
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        print ("[DEBUG]: enter function {func}()".format(
            func=self.func.__name__))
        return self.func(*args, **kwargs)
@logging
def say(something):
    print ("say {}!".format(something))
say('hello')



E:\python\python.exe E:/django工程/第20章/app01/cehi3.py
[DEBUG]: enter function say()
say hello!



本身改編的基於類實現的裝飾器

# -*- coding:UTF-8 -*-
class logging(object):
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        print ("[DEBUG]: enter function")
        return self.func(*args, **kwargs)
@logging
def say(something):
    print ("say",something)
say('hello')

ssh://root@192.168.0.75:22/usr/bin/python -u /app/py_code/test3.py
[DEBUG]: enter function
say hello


帶參數的類裝飾器
若是須要經過類形式實現帶參數的裝飾器,那麼會比前面的例子稍微複雜一點。那麼在構造函數裏接受的就不是一個函數,而是傳入的參數。經過類把這些參數保存起來。而後在重載__call__方法是就須要接受一個函數並返回一個函數。


class logging(object):
    def __init__(self, level='INFO'):
        self.level = level
        
    def __call__(self, func): # 接受函數
        def wrapper(*args, **kwargs):
            print "[{level}]: enter function {func}()".format(
                level=self.level,
                func=func.__name__)
            func(*args, **kwargs)
        return wrapper  #返回函數

@logging(level='INFO')
def say(something):
    print "say {}!".format(something)

E:\python\python.exe E:/django工程/第20章/app01/cehi3.py
[INFO]: enter function say()
say hello!



帶參數的類裝飾器--本身改編的

# -*- coding:UTF-8 -*-
class logging(object):
    def __init__(self, level='INFO'):
        self.level = level

    def __call__(self, func): # 接受函數
        def wrapper(*args, **kwargs):
            print ("[{level}]: enter function")
            func(*args, **kwargs)
        return wrapper  #返回函數

@logging(level='INFO')
def say(something):
    print ("say",something)
say('hello')

內置裝飾器

python中@property裝飾器的用法

參照:https://blog.csdn.net/wzqnls/article/details/53587049


不使用@property實現類

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

    def get_name(self):
        return self.name

    def set_name(self, new_name):
        self.name = new_name

    def del_name(self):
        del self.name
boy = Boy('Tom')
print(boy.get_name())



E:\python\python.exe E:/django工程/第20章/app01/cehi3.py
Tom
Alice

使用@property實現上述類

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

        @property
        def name(self):
            return self._name

        # 下面這個裝飾器是由上面的@property衍生出來的裝飾器
        @name.setter
        def name(self,new_name):
            self._name = new_name

        @name.deleter
        def name(self):

            del self._name
boy = Boy('Tom')
boy.name = 'white dog'
print(boy.name)
del boy.name

實例二:

class Animal(object):
    def __init__(self, name, age):
        self._name = name
        self._age = age
        self._color = 'Black'

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, value):
        if value > 0 and value < 100:
            self._age = value
        else:
            self._age = 0
            # print 'invalid age value.'

    @property
    def color(self):
        return self._color

    @color.setter
    def color(self, style):
        self._color = style


a = Animal('black dog', 3)
a.name = 'white dog'
a.age = 300
print ('Name:', a.name)
print ('Age:', a.age)
 
相關文章
相關標籤/搜索