The difference between the python keyword parameter and the named keyword parameter, and the python keyword

Source: Internet
Author: User

The difference between the python keyword parameter and the named keyword parameter, and the python keyword
Keyword Parameter

Variable parameters allow you to input 0 or any parameter. These variable parameters are automatically assembled into a tuple during function calling. Keyword parameters allow you to input 0 or any parameters with parameter names. These keyword parameters are automatically assembled into a dict in the function. See the example:

def person(name, age, **kw):    print('name:', name, 'age:', age, 'other:', kw)

FunctionpersonExcept for required parametersnameAndageIn addition, keyword parameters are also accepted.kw. When calling this function, you can only input the required parameters:

>>> person('Michael', 30)name: Michael age: 30 other: {}

You can also input any number of keyword parameters:

>>> person('Bob', 35, city='Beijing')name: Bob age: 35 other: {'city': 'Beijing'}>>> person('Adam', 45, gender='M', job='Engineer')name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}

What is the use of keyword parameters? It can expand functions of functions. For examplepersonIn the function, we ensure that we can receivenameAndageHowever, if the caller is willing to provide more parameters, we can also receive them. Imagine that you are working on a user registration function. Except that the user name and age are mandatory, other functions are optional. Using Keyword parameters to define this function can meet the registration requirements.

Similar to variable parameters, You can assemble a dict and then convert the dict into a keyword parameter:

>>> extra = {'city': 'Beijing', 'job': 'Engineer'}>>> person('Jack', 24, city=extra['city'], job=extra['job'])name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}

Of course, the above complex calls can be simplified:

>>> extra = {'city': 'Beijing', 'job': 'Engineer'}>>> person('Jack', 24, **extra)name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}

**extraIndicatesextraAll key-values of this dict are passed into the function using the keyword Parameter**kwParameter,kwYou will get a dict. Note thatkwThe obtained dict isextraA copykwWill not affectextra.

Name keyword Parameter

For keyword parameters, function callers can input any unrestricted keyword parameters. As for what is passed in, you need to passkwCheck.

Stillperson()For example, we want to check whether there arecityAndjobParameters:

Def person (name, age, ** kw): if 'city' in kw: # pass if 'job' in kw with the city parameter: # job Parameter pass print ('name: ', name, 'Age:', age, 'other: ', kw)

However, the caller can still pass in unrestricted keyword parameters:

>>> person('Jack', 24, city='Beijing', addr='Chaoyang', zipcode=123456)

If you want to restrict the name of a keyword parameter, you can use the name keyword parameter. For example, onlycityAndjobAs a keyword parameter. The function defined in this method is as follows:

def person(name, age, *, city, job):    print(name, age, city, job)

And keyword Parameters**kwDifferent, the name keyword parameter requires a special separator*,*The following parameters are considered as named keyword parameters.

The call method is as follows:

>>> person('Jack', 24, city='Beijing', job='Engineer')Jack 24 Beijing Engineer

If a variable parameter already exists in the function definition, a special separator is no longer needed for the name keyword parameter that follows.*Now:

def person(name, age, *args, city, job):    print(name, age, args, city, job)

The parameter name must be input for the naming keyword parameter, which is different from the location parameter. If the parameter name is not input, an error is returned during the call:

>>> person('Jack', 24, 'Beijing', 'Engineer')Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: person() takes 2 positional arguments but 4 were given

The parameter name is missing during the call.cityAndjob, The Python interpreter regards these four parameters as location parameters,person()The function only accepts two location parameters.

The name keyword parameter can have a default value to simplify the call:

def person(name, age, *, city='Beijing', job):    print(name, age, city, job)

Because of the name keyword ParametercityIt has a default value. You can skip this parameter when calling it.cityParameters:

>>> person('Jack', 24, job='Engineer')Jack 24 Beijing Engineer

When using a named keyword parameter, note that if there is no variable parameter, you must add*As a special separator. If*, The Python interpreter cannot identify location parameters and naming keyword parameters:

Def person (name, age, city, job): # missing *, city and job are regarded as location parameters pass

Def person (name, age, city, job): # missing *, city and job are regarded as location parameters pass

There are two types of naming keyword parameters:

def person(name,age,*,city,job)

Or

def person(name,age,*city)


Related Article

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.