Python Standard library--functools.partial

Source: Internet
Author: User

Official address: https://docs.python.org/3.6/library/functools.html

A. Brief introduction:

The Functools module is used for higher order functions: Functions that act on or return other functions. Generally, any callable object can be handled as a function of the purpose of this module.

Functools.partial returns a callable partial object, using partial (FUNC,*ARGS,**KW), which Func must be passed in, and requires at least one args or kw parameter.

Create a function function that implements three numbers, and if one or more of the parameters are not changed, you can use partial to instantiate an object that passed in the Add and 12 parameters, as shown in the two parameters, and the sum of three numbers.

Two. Partial source code Analysis: 1.__new__ Method section
  1. class partial:
  2. "" " New function with partial application of the given arguments
  3. and keywords.
  4. """
  5. # # #__SLOTS__ only allow classes to have this property and cannot dynamically add other properties
  6. __slots__ = "func", "args", "keywords", "__dict__", "__weakref__"
  7. # # #__new__方法生成实例对象
  8. def __new__(*args, **keywords):
  9. # # #实例化对象时传入参数的限定, cannot be empty, the number of parameters is greater than or equal to 2, which explains that at least one or more args or Kw,func is a callable object that must be passed in
  10. if not args:
  11. Raise TypeError ("descriptor ' __new__ ' of the partial needs an argument")
  12. if Len (args) < 2:
  13. Raise TypeError ("type ' partial ' takes at least one argument")
  14. CLS, func, *args = args # args= (Cls,func,*args)
  15. If not callable (func):
  16. Raise TypeError ("The first argument must be callable")
  17. # # # Positional parameters are passed in as tuples
  18. args = tuple (args)
    1.  ## #hasattr这块我也没有咋个明白, do not know where to apply, from the perspective of use, Incoming function Func should have a property or a method, if you know please tell me
    2.      if hasattr (Func, "func"):
    3.      args = Func.args + args
    4.  tmpkw = func.keywords.copy ()
    5.  tmpkw.update (keywords)
    6.  keywords = tmpkw
    7.  del tmpkw
    8.  func = Func.func
    9.  ## #创建一个实例对象本身
    10.      self = Super (partial, CLS). __new__ (CLS)
    11.  ## #动态的添加属性
    12.      self.func = Func
    13.      self.args = args
    14.  self.keywords = keywords
    15.  return self

The above code creates an instance object (P=partial (func,*args,**kw)) and adds properties to the object itself.

2. __call__ Method Section

Look at the callable part, the partial instantiation of the object is a callable, because in the partial write the __call__ method, look at the source:

  1. # # # #在使用p () automatically calls the __call__ method
  2. def __call__(*args, **keywords):
  3. if not args:
  4. Raise TypeError ("descriptor ' __call__ ' of the partial needs an argument")
  5. Self, *args = args
  6. # # #将位置参数和关键字参数分别合在一起, when using P (), only the partial parameters are passed, this is for our convenience, do not repeat the parameter passed in, and in the __call__ method, the parameters required by Func are all passed in
  7. Newkeywords = Self.keywords.copy ()
  8. Newkeywords.update (keywords)
  9. ###*self.args is a *args in partial (func,*args,**kw)
  10. return Self.func (*self.args, *args, **newkeywords)

When using P (*args,**keywords), the __call__ method is called automatically, which is the reason that the generated object can be called, Self is instantiating the object itself, *args, **kw is the parameter we passed in the function func, but only some of the parameters are passed in. This is also the role of the partial, so the positional and keyword parameters in partial (func,*args,**kw) and P (*args,**keywords) are also passed into the function Func to implement function functions. The function realization of partial in the official website is equivalent to:

    1. def partial(func, *args, **keywords):
    2. def newfunc(*fargs, **fkeywords):
    3. Newkeywords = Keywords.copy ()
    4. Newkeywords.update (Fkeywords)
    5. return func (*args, *fargs, **newkeywords)
    6. Newfunc.func = Func
    7. Newfunc.args = args
    8. Newfunc.keywords = Keywords
    9. return Newfunc

When the partial function is called, the Newfunc function object is returned, so that f=partial (add,12) is quite f=newfunc, so f is a callable object, so f----is equivalent to Newfunc > integrates parameter integration into Func and returns Func to implement its functionality.

Python standard library--functools.partial

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.