Python 中的 Decorator(装饰器) 是一个接收另一个函数作为参数的函数。argument 函数是 decorator 要装饰的函数。参数函数的行为由装饰器扩展,而无需实际修改它。
在本章中,我们将学习如何使用 Python 装饰器。
定义函数装饰器
Python 中的函数是一阶对象。这意味着它可以作为参数传递给另一个函数,就像其他数据类型(如数字、字符串或列表等)一样。也可以在另一个函数中定义一个函数。这样的函数称为 嵌套函数。此外,一个函数也可以返回其他函数。
装饰器函数的典型定义如下 -
def decorator(arg_function): #arg_function to be decorated
def nested_function():
#this wraps the arg_function and extends its behaviour
#call arg_function
arg_function()
return nested_function
这是一个普通的 Python 函数 -
print ("hello")
你现在可以通过将它传递给 decorator 来装饰这个函数来扩展它的行为 -
如果现在执行此函数,它将显示由 decorator 扩展的输出。
Python 装饰器示例
练习以下示例来理解 Python 装饰器的概念 -
示例 1以下代码是装饰器的一个简单示例 -
def my_function(x):
print("The number is=",x)
def my_decorator(some_function,num):
def wrapper(num):
print("Inside wrapper to check odd/even")
if num%2 == 0:
ret= "Even"
else:
ret= "Odd!"
some_function(num)
return ret
print ("wrapper function is called")
return wrapper
no=10
my_function = my_decorator(my_function, no)
print ("It is ",my_function(no))
my_function() 只是打印出接收到的号码。但是,通过将其传递给 my_decorator 来修改其行为。内部函数接收数字并返回它是奇数还是偶数。上述代码的输出为 −
wrapper function is called
Inside wrapper to check odd/even
The number is= 10
It is Even
示例 2
装饰函数的一种优雅方法是在其定义之前提及装饰器的名称,并在其前面加上 @ 符号。上面的例子是用这个表示法重写的 -
def my_decorator(some_function):
def wrapper(num):
print("Inside wrapper to check odd/even")
if num%2 == 0:
ret= "Even"
else:
ret= "Odd!"
some_function(num)
return ret
print ("wrapper function is called")
return wrapper
@my_decorator
def my_function(x):
print("The number is=",x)
no=10
print ("It is ",my_function(no))
Python 的标准库定义了以下内置装饰器:
@classmethod Decorator
类方法是一个内置函数。它将方法转换为类方法。类方法不同于实例方法。类中定义的实例方法由其对象调用。该方法接收到 self 引用的隐式对象。另一方面,类方法隐式地接收类本身作为第一个参数。
语法
为了声明类方法,使用以下装饰器表示法 -
class Myclass:
@classmethod
def mymethod(cls):
#....
@classmethod 形式是前面描述的函数装饰器的形式。mymethod 接收对类的引用。它可以由类及其对象调用。这意味着 Myclass.mymethod 和 Myclass().mymethod 都是有效的调用。
@classmethod Decorator 示例
让我们在以下示例的帮助下理解类 method 的行为 -
class counter:
count=0
def __init__(self):
print ("init called by ", self)
counter.count=counter.count+1
print ("count=",counter.count)
@classmethod
def showcount(cls):
print ("called by ",cls)
print ("count=",cls.count)
c1=counter()
c2=counter()
print ("class method called by object")
c1.showcount()
print ("class method called by class")
counter.showcount()
在类定义中,count 是一个类属性。__init__() 方法是构造函数,显然是一个实例方法,因为它接收 self 作为对象引用。声明的每个对象都调用此方法,并将 count 递增 1。
@classmethod 装饰器将 showcount() 方法转换为类方法,该方法接收对类的引用作为参数,即使它被其对象调用。即使 c1 对象调用 showcount 也可以看到,它会显示 counter 类的引用。
它将显示以下输出 -
count= 1
init called by <__main__.counter object at 0x000001D32DAC8710>
count= 2
class method called by object
called by <class '__main__.counter'>
count= 2
class method called by class
called by <class '__main__.counter'>
@staticmethod Decorator
static方法也是 Python 标准库中的内置函数。它将方法转换为静态方法。静态方法不会收到任何引用参数,无论是由类的实例还是类本身调用。以下用于在类中声明静态方法的表示法 -
语法
class Myclass:
@staticmethod
def mymethod():
#....
即使 Myclass.mymethod 和 Myclass().mymethod 都是有效调用,静态方法也不会收到任何一个引用。
@staticmethod Decorator 示例
counter 类修改如下 −
class counter:
count=0
def __init__(self):
print ("init called by ", self)
counter.count=counter.count+1
print ("count=",counter.count)
@staticmethod
def showcount():
print ("count=",counter.count)
c1=counter()
c2=counter()
print ("class method called by object")
c1.showcount()
print ("class method called by class")
counter.showcount()
和以前一样,类属性 count 在 __init__() 方法中声明每个对象时递增。但是,由于 mymethod() ,作为静态方法不会接收 self 或 cls 参数。因此,类属性 count 的值与对 counter 的显式引用一起显示。
上述代码的输出如下 -
count= 1
init called by <__main__.counter object at 0x000002512ED48668>
count= 2
class method called by object
count= 2
class method called by class
count= 2
@property Decorator
Python 的 property() 内置函数是用于访问类的实例变量的接口。@property 修饰器将实例方法转换为具有相同名称的只读属性的 “getter”,并将该属性的文档字符串设置为“Get the current value of the instance variable”。
您可以使用以下三个装饰器来定义属性 -
- @property − 将方法声明为属性。
- @<property-name>.setter: − 指定将值设置为属性的属性的 setter 方法。
- @<property-name>.deleter − 将 delete 方法指定为一个属性,该属性 删除属性。
property() 函数返回的属性对象具有 getter、setter 和 delete 方法。
property(fget=None, fset=None, fdel=None, doc=None)
fget 参数是 getter 方法,fset 是 setter 方法。它可以选择将 fdel 作为删除对象的方法,而 doc 是文档字符串。
语法
property() 对象的 setter 和 getter 也可以使用以下语法分配。
speed = property()
speed=speed.getter(speed, get_speed)
speed=speed.setter(speed, set_speed)
其中 get_speed() 和 set_speeds() 是 Car 类中检索值并将其设置为实例可变 speed 的实例方法。
上述语句可以通过 @property 装饰器实现。使用 decorator car 类被重写为 -
@property Decorator 示例
class car:
def __init__(self, speed=40):
self._speed=speed
return
@property
def speed(self):
return self._speed
@speed.setter
def speed(self, speed):
if speed<0 or speed>100:
print ("speed limit 0 to 100")
return
self._speed=speed
return
c1=car()
print (c1.speed) #calls getter
c1.speed=60 #calls setter
Property decorator 是处理实例属性的非常方便和推荐的方法。