Detailed explanation of the function of python naming keyword parameter

  • 2021-10-13 08:02:38
  • OfStack

1. Description

*, nkw means naming keyword parameter, which is the name of keyword parameter that users want to input. The definition method is to append * before nkw.

2. Function

Restrict the parameter names conveyed by the caller.

3. Examples


#  Named keyword parameter 
def print_info4(name, age=18, height=178, *, weight, **kwargs):
  '''
   Print information function 4 Add a named keyword parameter 
  :param name:
  :param age:
  :param height:
  :param weight:
  :param kwargs:
  :return:
  '''
  print('name: ', name)
  print('age: ', age)
  print('height: ', height)
  print('keyword: ', kwargs)
  print('weight: ', weight)
print_info4('robin', 20, 180, birth='2000/02/02', weight=125)

Extension of knowledge points:

Keyword parameter

Variable arguments allow you to pass in 0 or any arguments that are automatically assembled into an tuple when the function is called. Keyword parameters allow you to pass in 0 or any parameter with parameter names, which are automatically assembled into 1 dict inside the function.
In the form of:


>>> def person(name,age,**kw):
	print("name:",name,"age:",age,"other:",kw)
>>> person("bbj",23,city="hefei",habit="basketball")
name: bbj age: 23 other: {'city': 'hefei', 'habit': 'basketball'}
>>> 

As far as I understand it, keyword parameters can be passed in countless self-named parameters when calling, which means self-named keywords. All keyword parameters are automatically assembled into a dictionary


Related articles: