Python study notes day5 - 03 function parameters - positional parameters and default parameters

When calling a function with positional
    parameters, the parameters passed into the function are assigned to the parameters of the function in order of position.
#The function that calculates the power       
        def power(x, n):
            s = 1
            while n > 0:
                n = n - 1
                s = s * x
            return s
        When using power(1,2), it will be based on the position order, will 1 is assigned to x and 2 is assigned to n.

Default parameters
    If you want to not specify the exponent, the default is to calculate according to the square, you can specify the default parameters of the function.
#The function to calculate the power, the default is to calculate the square
        def power(x, n=2):
            s = 1
            while n > 0:
                n = n - 1
                s = s * x
            return s
        Use power(10) directly, then calculate 10 squared. To calculate 5 to the 3rd power, use power(5, 3).
       
    Using default parameters can simplify the function call, but there are a few points to pay attention to when setting default parameters:
        1. The required parameters are in the front, and the default parameters are in the back, otherwise an error will be reported.
        2. When the function has multiple parameters, put the parameters with large changes in the front, the parameters with small changes in the back, and the parameters with small changes can be used as default parameters.
        3. Default parameters must be specified as immutable objects!
The use
of default parameters #Here is a detailed explanation of some of the default parameters.
    #First define a function to register identity information, using 4 parameters: name, age, gender, nationality.
    #Here, age, gender and nationality can be set as default parameters from a certain dimension as needed, for example: most of the students in the class are the same age, most of the football players are of the same gender, and the nationalities are even more consistency.
   
    def info(name,age,sex,intl):
        print(name,'from',intl,'is a',age,'year-old',sex,'child')
        return None
       
    >>> info('small A', 10, 'Male', 'China')
    Little A is from China and is a 10-year-old boy
   
    # Suppose there are 10 people now, all of them are boys of Chinese nationality, two of them are 14 and 12 years old respectively is 10 years old, and everyone else is 10 years old, so this input operation is very suitable for default parameters.
   
    def info(name,age=10,sex='male',intl='Chinese'):
        print(name,'from',intl,'is a',age,'year-old',sex,'child' )
        return None
       
    >>> info('Little B'



    >>> info('Little D', 12)
    Little D is from China and is a 12 year old boy
    >>> info(age=14,name='Little E')
    Little E is from China and is a 14 year old boy
   
    #It can be seen that when using default parameters, it is actually very flexible. You can pass in parameters according to the order, or you can specify the parameter name assignment method to provide parameters in different order.
   
The pit of default parameters: must be set to immutable objects.
    Let's first try setting the default parameter to a mutable object:
        >>> def nn(name,ext=[]):
        ... ext.append('over')
        ... print(name,ext)
        . ..
        >>> nn('a')
        a ['over']
        >>> nn('a')
        a ['over', 'over'
    ] You can see that when list is used as the default parameter, unexpected results occur.
    When the function is defined, the value of the default parameter ext is calculated. Here it is []. The ext parameter is actually a variable pointing to []. If the content of the ext parameter (that is, []) is changed, the following The content of the default parameter changes when the function is called again, pointing to the modified [] instead of the [] when the function was first defined.
   
    In order to avoid the above situation, you can use this method to solve:
        >>> def nn(name,ext=None):
        ... if ext is None:
        ... ext = []
        ... ext.append('over')
        ... print(name,ext)
        .. .
        >>> nn('aa')
        aa ['over']
        >>> nn('aa')
        aa ['over']
        >>> nn('aa','bb')
        aa bb
       
use immutable objects It can reduce errors caused by modifying data. Since the object remains unchanged, reading the object at the same time in a multi-task environment does not require locking, and the reading action can be performed at the same time. When writing a program, if it can be designed as an immutable object, design it as an immutable object as much as possible.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325244829&siteId=291194637