函数在python中属于一等公民,即

  • 函数是一个对象
  • 函数内部可以定义函数,也可以作为参数传递

在python中,装饰器(Decorators)是非常强大且有用的工具,它允许程序员修改函数或类的行为。装饰器允许我们包装另一个函数以扩展包装函数的行为,而无需对其进行永久性修改。

在Decorators中,将函数作为另一个函数的参数,然后在包装函数内部调用。

如下所示

@gfg_decorator
def hello_decorator(): 
	print("Gfg") 

'''Above code is equivalent to - 

def hello_decorator(): 
	print("Gfg") 
	
hello_decorator = gfg_decorator(hello_decorator)'''

在上面的代码中,gfg_decorator是一个可调用函数,将在另一个可调用函数hello_decorator函数的顶部添加一些代码,并返回包装函数。

装饰者可以修改行为

# defining a decorator 
def hello_decorator(func): 

	# inner1 is a Wrapper function in 
	# which the argument is called 
	
	# inner function can access the outer local 
	# functions like in this case "func" 
	def inner1(): 
		print("Hello, this is before function execution") 

		# calling the actual function now 
		# inside the wrapper function. 
		func() 

		print("This is after function execution") 
		
	return inner1 


# defining a function, to be called inside wrapper 
def function_to_be_used(): 
	print("This is inside the function !!") 


# passing 'function_to_be_used' inside the 
# decorator to control its behavior 
function_to_be_used = hello_decorator(function_to_be_used) 


# calling the function 
function_to_be_used() 

上面的代码输出为

Hello, this is before function execution
This is inside the function !!
This is after function execution

利用装饰器,可以很容易地写一个计算函数运行时间的函数,如下所示

# importing libraries 
import time 
import math 

# decorator to calculate duration 
# taken by any function. 
def calculate_time(func): 
	
	# added arguments inside the inner1, 
	# if function takes any arguments, 
	# can be added like this. 
	def inner1(*args, **kwargs): 

		# storing time before function execution 
		begin = time.time() 
		
		func(*args, **kwargs) 

		# storing time after function execution 
		end = time.time() 
		print("Total time taken in : ", func.__name__, end - begin) 

	return inner1 



# this can be added to any function present, 
# in this case to calculate a factorial 
@calculate_time
def factorial(num): 

	# sleep 2 seconds because it takes very less time 
	# so that you can see the actual difference 
	time.sleep(2) 
	print(math.factorial(num)) 

# calling the function. 
factorial(10) 

上面的例子中,被装饰的函数都没有返回值,如果有呢?看下面这个例子

def hello_decorator(func): 
	def inner1(*args, **kwargs): 
		
		print("before Execution") 
		
		# getting the returned value 
		returned_value = func(*args, **kwargs) 
		print("after Execution") 
		
		# returning the value to the original frame 
		return returned_value 
		
	return inner1 


# adding decorator to the function 
@hello_decorator
def sum_two_numbers(a, b): 
	print("Inside the function") 
	return a + b 

a, b = 1, 2

# getting the value through return of the function 
print("Sum =", sum_two_numbers(a, b)) 

呵呵,就是这样吧.

参考


我很好奇