Examples of the use of variable length parameters in Python? __python

Source: Internet
Author: User
Tags in python

Careful use of variable length parameters
Python supports variable-length parameter lists, which can be implemented by *arg, **kwargs these two special syntaxes. The following examples are used for variable length parameters:
* Use *args to implement the variable parameter list: *args with Accept
A parameter list wrapped as a tuple to pass a non-critical parameter, and the number of parameters can be arbitrary.

def sumfun (*args): Result
    = 0
    for x in args[0:]: result
      + = x return result
print Sumfun (2, 4)
pri NT Sumfun (1,2,3,4,5)
print Sumfun ()
Use **kwargs to receive a list of keyword parameters in a dictionary, where the dictionary's key-value pairs represent the parameter names and values of the mutable arguments, respectively.
def category_table (**kwargs):
    for Name, value in Kwargs.items ():
        print ' {0} is a kind of {1} '. Format (name, value) C9/>category_table (apple= ' fruit ', carrot= ' vegetable ')
category_table (BMW = ' car ')
In a function, the normal parameters, the default parameters, and the two types of variable parameters are defined.
def set_axis (x, y xlabel= ' x ', ylable= ' y ', *args, **kwargs): Pass
    
It is appropriate to use variable parameters in the following scenarios
def mydecorator (fun):
    def new (*args, **kwargs): Return
      Fun (*args, **kwargs) return
    new

If the number of parameters is indeterminate, consider using variable-length parameters.

It is used to implement the polymorphism of a function or, in the case of inheritance, some methods in which the parent class needs to be invoked.

Class A (object):
    def somefun (self, p1, p2):
        Pass
class B (a):
    def myfun (self, p3, *args, **kwargs):
        Super (B, self). Somefun (*args, **kwargs)

This digest is from the 91 recommendations for writing high-quality code to improve Python programs

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.