当前位置:Gxlcms > Python > Python实现partial改变方法默认参数

Python实现partial改变方法默认参数

时间:2021-07-01 10:21:17 帮助过:57人阅读

在Python的标准库中,functools库中有很多对方法有操作的封装功能,partial Objects就是其中之一,他可以实现对方法参数默认值的修改。本文就以实例代码说明这一功能。

下面就看下简单的应用测试实例。具体代码如下:

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #python2.7x
  4. #partial.py
  5. #authror: orangleliu
  6. '''
  7. functools 中Partial可以用来改变一个方法默认参数
  8. 1 改变原有默认值参数的默认值
  9. 2 给原来没有默认值的参数增加默认值
  10. '''
  11. def foo(a,b=0) :
  12. '''
  13. int add'
  14. '''
  15. print a + b
  16. #user default argument
  17. foo(1)
  18. #change default argument once
  19. foo(1,1)
  20. #change function's default argument, and you can use the function with new argument
  21. import functools
  22. foo1 = functools.partial(foo, b=5) #change "b" default argument
  23. foo1(1)
  24. foo2 = functools.partial(foo, a=10) #give "a" default argument
  25. foo2()
  26. '''
  27. foo2 is a partial object,it only has three read-only attributes
  28. i will list them
  29. '''
  30. print foo2.func
  31. print foo2.args
  32. print foo2.keywords
  33. print dir(foo2)
  34. ##默认情况下partial对象是没有 __name__ __doc__ 属性,使用update_wrapper 从原始方法中添加属性到partial 对象中
  35. print foo2.__doc__
  36. '''
  37. 执行结果:
  38. partial(func, *args, **keywords) - new function with partial application
  39. of the given arguments and keywords.
  40. '''
  41. functools.update_wrapper(foo2, foo)
  42. print foo2.__doc__
  43. '''
  44. 修改为foo的文档信息了
  45. '''

这样如果我们使用一个方法总是需要默认几个参数的话就可以,先做一个封装然后不用每次都设置相同的参数了。

希望本文所述方法对大家的Python程序设计有一定的借鉴与帮助价值。

人气教程排行