Discuss / Python / 摸摸鱼

摸摸鱼

Topic source

v贝塔v

#1 Created at ... [Delete] [Delete and Lock User]

这个让log变成可以无入参和有入参两种形式还想了蛮久的

# -*- coding: UTF-8 -*-

from __future__ import print_function # 解决python2 不能使用print(end='')
import functools

def log(argue):
	def decorate(func):
		@functools.wraps(func)
		def wrapper(*arg,**kw):
			if type(argue) == str:
				print('%s '%argue,end='') # 这里argue由于闭包变成了类似全局变量,因此可以引用
			print('%s'%func.__name__)
			return func(*arg,**kw)
		return wrapper
	if type(argue) != str:
		return decorate(argue) # 执行函数decorate并返回结果,入参为被装饰的函数func
	else:
		return decorate  # 将函数decorate看作对象,返回该函数
		
@log # func1 = log(func1)
def func1():
	pass

@log('execute') # func2 = log('execute')(func2),即先执行A = log('execute'),再执行A(func2)
def func2():
	pass

func1()
func2()
print(func1.__name__) # 检验函数签名是否保持不变
print(func2.__name__)

v贝塔v

#2 Created at ... [Delete] [Delete and Lock User]

关键还是在于 @log这个的理解吧,只写@log传入的是函数签名,而写成@log('execute')则传入的是修饰字符串,利用返回的wrapper函数作为最终的装饰器@log

细节还挺多的


  • 1

Reply