文章目录
一、什么是 python 装饰器
装饰器是一个 python 的函数,可以让其他函数在不增加任何代码的情况下增加功能,也就是将其他函数“包装”起来,可以简化代码,做到代码重用。
装饰器能接收一个函数作为输入,返回值也是一个函数对象。
二、装饰器的使用
def a_new_decorator(a_func):
def wrapTheFunction():
print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
return wrapTheFunction
def a_function_requiring_decoration():
print("I am the function which needs some decoration to remove my foul smell")
a_function_requiring_decoration()
#outputs: "I am the function which needs some decoration to remove my foul smell"
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
#now a_function_requiring_decoration is wrapped by wrapTheFunction()
a_function_requiring_decoration()
#outputs:I am doing some boring work before executing a_func()
# I am the function which needs some decoration to remove my foul smell
# I am doing some boring work after executing a_func()
从上面这个例子可以看出,装饰器就是能把扔进他的函数做一个装饰。@符号是装饰器的语法糖,使用@符号的写法如下:
@a_new_decorator
def a_function_requiring_decoration():
"""Hey you! Decorate me!"""
print("I am the function which needs some decoration to "
"remove my foul smell")
a_function_requiring_decoration()
#outputs: I am doing some boring work before executing a_func()
# I am the function which needs some decoration to remove my foul smell
# I am doing some boring work after executing a_func()
#the @a_new_decorator is just a short way of saying:
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
我们都知道函数有一些原信息,如 docstring, _ _name _ _等,如果使用装饰器的话,原函数的元信息就会被装饰器的信息所代替,如下所示:
print(a_function_requiring_decoration.__name__)
# Output: wrapTheFunction
所以 python 提供了一个装饰器:functools.wraps
,wraps
本身就是一个装饰器,能把原函数的元信息拷贝到装饰器函数中,使得装饰器函数有和原函数一样的元信息。
from functools import wraps
def a_new_decorator(a_func):
@wraps(a_func)
def wrapTheFunction():
print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
return wrapTheFunction
@a_new_decorator
def a_function_requiring_decoration():
"""Hey yo! Decorate me!"""
print("I am the function which needs some decoration to "
"remove my foul smell")
print(a_function_requiring_decoration.__name__)
# Output: a_function_requiring_decoration
所以,典型的蓝本如下:
from functools import wraps
def decorator_name(f):
@wraps(f)
def decorated(*args, **kwargs):
if not can_run:
return "Function will not run"
return f(*args, **kwargs)
return decorated
@decorator_name
def func():
return("Function is running")
can_run = True
print(func())
# Output: Function is running
can_run = False
print(func())
# Output: Function will not run
三、装饰器类型
常见的内置装饰器有三种:
- @property
- @staticmethod
- @classmethod
3.1 特性装饰器 @property
@property: 可以把一个方法变成其同名属性,以支持实例访问和调用
在函数前面加上 @property 后,就可以把 getter
和 setter
方法变成属性,定义 getter
方法就是一个只读属性,定义 setter
方法就是一个可读可写的。
class Student(object):
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
# birth 是可读写属性,age 是只读属性,注意这里 birth 函数返回的是 self._birth,不能返回 self.birth
class Student(object):
@property
def birth(self):
return self._birth
@birth.setter
def birth(self, value):
self._birth = value
@property
def age(self):
return 2015 - self._birth
3.2 类装饰器 @classmethod
@classmethod : 用来指定一个类的方法为类方法,其修饰的方法不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等
传入的 cls 通常用作类方法的第一参数,对于普通的类来说,要使用的话必须先进行实例化,而在一个类中,某个函数前面加上了 classmethod 或 staticmethod,这个函数就可以不用实例化,可以直接通过类名进行调用。
class A:
@classmethod
def func(cls, arg1, arg2):
...
例子:
import time
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@classmethod
def today(cls):
t = time.localtime()
return cls(t.tm_year, t.tm_mon, t.tm_mday)
调用:
a = Date(2020, 4, 6)
b = Date.today()
3.3 静态装饰器 @staticmethod
改变一个方法为静态方法,静态方法不需要传递隐性的第一参数,静态方法的本质类型就是一个函数。
静态方法可以直接通过类进行调用,也可以通过实例进行调用:
import time
class Date:
def __init__(self,year,month,day):
self.year=year
self.month=month
self.day=day
@staticmethod
def now(): #用Date.now()的形式去产生实例,该实例用的是当前时间
t=time.localtime() #获取结构化的时间格式
return Date(t.tm_year,t.tm_mon,t.tm_mday) #新建实例并且返回
@staticmethod
def tomorrow():#用Date.tomorrow()的形式去产生实例,该实例用的是明天的时间
t=time.localtime(time.time()+86400)
return Date(t.tm_year,t.tm_mon,t.tm_mday)
a = Data(2020, 4, 6)
print(a.year, a.month, a.day)
# 静态方法无需实例化
b = Data.now()
print(b.year, b.month, b.day)
c = Data.tomorrow
print(c.year, c.month, c.day)
# 静态方法也可实例化后调用
a.now()
3.4 抽象方法装饰器 @abstractmethod
抽象方法表示基类的中一个方法,在基类中没有实现,所以不能被实例化,在子类中实现了以后才能被实例化,继承了含有抽象方法基类类的子类必须复写所有的抽象方法,未被 @abstractmethod 修饰的可以不重写。
abstractmethod 的好处在哪里:
可以把某个方法装饰成抽象的方法,类似于接口,可以用具有同一属性的对象实现同一个抽象的方法,这样无论是维护还是从代码结构来说,都比较清晰。
from abc import ABC, abstractmethod
class a(ABC):
@abstractmethod
def writeblog(self):
pass
class b(a):
def writeblog(self):
print('writing blogs')
if __name__=='__main__':
# 使用如下的方法会报错,因为被抽象装饰器装饰的方法需要不能直接实例化
c = a()
# 可以让 b 继承 a,然后在 b 里边重写被装饰的 writeblog 的方法,然后实例化 b
c = b()
c.writeblog() # output 'writing blogs'