Gitlib Gitlib
首页
  • 分类
  • 标签
  • 归档
  • Golang开发实践万字总结
  • MySQL核心知识汇总
  • Redis实践总结
  • MQ实践万字总结
  • Docker数据持久化总结
  • Docker网络模式深度解读
  • 常用游戏反外挂技术总结
  • 读书笔记
  • 心情杂货
  • 行业杂谈
  • 友情链接
关于我
GitHub (opens new window)

Ravior

以梦为马,莫负韶华
首页
  • 分类
  • 标签
  • 归档
  • Golang开发实践万字总结
  • MySQL核心知识汇总
  • Redis实践总结
  • MQ实践万字总结
  • Docker数据持久化总结
  • Docker网络模式深度解读
  • 常用游戏反外挂技术总结
  • 读书笔记
  • 心情杂货
  • 行业杂谈
  • 友情链接
关于我
GitHub (opens new window)
  • PHP

  • Golang

  • Python

    • Python使用lambda表达式
    • Python之线程池
    • Python之装饰器
    • Python之chardet模块使用
    • Python之copy模块使用
    • Python之functools模块使用
      • wraps
    • Python之hashlib模块使用
    • Python之json模块使用
    • Python之pickle模块使用
    • Python之pid模块使用
    • Python之pypinyin模块使用
    • Python之pyqrcode模块使用
    • Python之threading模块使用
    • Python之base64模块使用
    • Python项目Docker打包
  • Javascript

  • 其他语言

  • 编程语言
  • Python
Ravior
2014-07-10
目录

Python之functools模块使用

functools模块中主要包含了一些函数装饰器和便捷的功能函数,关于装饰器的介绍可见这里。

# wraps

# encoding:utf8
# python装饰器

def log(func):
	def wrapper(*args, **kwargs):
		print('call %s():' % func.__name__)
		print('args = {}'.format(*args))
		return func(*args, **kwargs)

	return wrapper


@log
def test(p):
    print(test.__name__ + " param: " + p)


print(test)
print(test.__name__)
test("I'm a param")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

输出结果:

<function wrapper at 0x10c86b668>
wrapper
call test():
args = I'm a param
wrapper param: I'm a param
1
2
3
4
5

了解装饰器的应该都知道,test其实是指向wapper函数的指针,所以test.__name__输出是wapper, functools里面的wraps可以把原函数的元信息拷贝到装饰器里面的func函数中,示例如下:

# encoding:utf8
# python装饰器
import functools

def log(func):
	# 能把原函数的元信息拷贝到装饰器里面的func函数中,函数的元信息包括docstring、name、参数列表等等
	@functools.wraps(func)
	def wrapper(*args, **kwargs):
		print('call %s():' % func.__name__)
		print('args = {}'.format(*args))
		return func(*args, **kwargs)

	return wrapper


@log
def test(p):
    print(test.__name__ + " param: " + p)
    
test("I'm a param")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

输出结果:

<function test at 0x10d6c4668>
test
call test():
args = I'm a param
test param: I'm a param
1
2
3
4
5

可以看到,test.__name__已经发生了变化。@wraps接受一个函数来进行装饰,并加入了复制函数名称、注释文档、参数列表等等的功能。这可以让我们在装饰器里面访问在装饰之前的函数的属性

#Python
上次更新: 2022/12/01, 11:09:34
Python之copy模块使用
Python之hashlib模块使用

← Python之copy模块使用 Python之hashlib模块使用→

最近更新
01
常用游戏反外挂技术总结
11-27
02
Golang开发实践万字总结
11-11
03
Redis万字总结
10-30
更多文章>
Theme by Vdoing | Copyright © 2011-2022 Ravior | 粤ICP备17060229号-3 | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式