How to pass through Python args and kwargs?

后端 未结 2 1079
甜味超标
甜味超标 2021-01-07 22:43

While I have a general understanding (I think) of Python\'s *args and **kwargs, I\'m having trouble understanding how to pass them from one function through to another. Her

相关标签:
2条回答
  • 2021-01-07 23:24

    You pass them with syntax mirroring the argument syntax:

    self.save_name_for(*args, **kwargs)
    

    Note that you do not need to pass in self; save_name_for is already bound.

    0 讨论(0)
  • 2021-01-07 23:28

    The * and ** operators are used in two different situations.

    1. When used as part of a function definition,

      def save_name_for(self, *args, **kwargs):
      

      it is used to signify an arbitrary number of positional or keyword arguments, respectively. The point to remember is that inside the function args will be a tuple, and kwargs will be a dict.

    2. When used as part of a function call,

      args = (1, 2)
      kwargs = {'last': 'Doe', 'first': 'John'}
      self.save_name_for(*args, **kwargs)
      

      the * and ** act as unpacking operators. args must be an iterable, and kwargs must be dict-like. The items in args will be unpacked and sent to the function as positional arguments, and the key/value pairs in kwargs will be sent to the function as keyword arguments. Thus,

      self.save_name_for(*args, **kwargs)
      

      is equivalent to

      self.save_name_for(1, 2, last='Doe', first='John')
      

    See also the saltycrane blog for an explanation with examples.

    0 讨论(0)
提交回复
热议问题