Python function learning II

Posted by crash58 on Sun, 13 Feb 2022 13:31:46 +0100

python custom function learning II
1, Change of parameters
1. Location parameters
Position parameter means that when transferring parameter value, it must correspond to the parameters defined by the function one by one, and the position cannot be disturbed.
For example, a user-defined function call with two fixed parameters

def test(name,age):
    print("full name%s,Age%s"%(name,str(age)))
test('Hai',11)

test(11,'Hai')

# The result is:
# full name Hai,Age 11   #Correct result
# Name 11,Age Hai   #Wrong result

The most common way to pass the value of a parameter is the position.

2. Keyword parameters
It is mainly to avoid errors in passing values. It provides a way of "parameter name = value", which displays the representation when calling the function, and does not need to consider the position order of parameters.
For example:

def test(name,age):
    print("full name%s,Age%s"%(name,str(age)))



test(name='Tim',age=20)   #All parameters are specified by "parameter name = value"
test(age=20,name='Tim')   #When specifying keyword parameters, the corresponding order of positions can be ignored
test('Tim',age=20)  #When partially specifying, the left side can not be specified, starting from the right side
# test(name='Tim',20)  #There will be an error. The method of specifying on the left and not on the right is not supported
# test(age=20,'Tim')   #error

The result is:

full name Tim,Age 20
 full name Tim,Age 20
 full name Tim,Age 20

3. Default value
The parameter is specified as the default value in advance. When no value is passed to the parameter, the parameter automatically selects the default value.

def test(name='',age=20):
    print('full name%s,Age%s'%(name,str(age)))
test(19)   #By default, the first default parameter is assigned a value
test()
test("Tim",18)
# The result is
# Name 19, age 20
# Name, age 20
# Name Tim, age 18

4. Indefinite length parameter

Python allows programmers to write variable length parameters to facilitate the number of values to be passed according to the actual situation when calling functions.
1) Pass any number of parameter values
Format: function name ([param1,param2,...,] * paramX) paramX parameter with "*", can receive any number of values. However, a user-defined function can only have one parameter with "*" and can only be placed in the rightmost parameter, otherwise an error will be reported when the user-defined function is executed.
For example:

def melon(name,*att):
    print(name)
    print(type(att)) #Print out the type of att
    s=''
    for i in att:
        s+=' '+i
    print(s)
melon('watermelon','sweet','circular')  #Call the custom function and pass in two values for any parameter

# The result is:
# watermelon   
# <class 'tuple'>  #Is a tuple type
#  Sweet round

2) Pass any number of key value pairs
Format: function name ([param1,param2,...,] * * paramX)
The usage of paramX parameter with * * is similar to that with *, except that the key value pair is passed.
For example:

def melon(name,**att):
    print(name)
    print(type(att))
    return att

print(melon("watermelon",taste='sweet',shape='circular',color='green'))

# results of enforcement
# watermelon
# The < class' dict '> att parameter is actually a dictionary type
# {'taste': 'sweet', 'shape': 'round', 'color': 'green'}

2, Pass tuples, lists, and dictionary values
Custom parameters can pass tuples, lists, and dictionary values

def melon(name,att):
    print(name)
    print(type(att))
    return att

#Transitive tuple
get1=melon('watermelon',('sweet','circular','green'))
print(get1)
# results of enforcement
# watermelon
# <class 'tuple'>
# ('sweet', 'round', 'green')




# #Delivery list
get2=melon('watermelon',['sweet','circular','green'])
print(get2)

#results of enforcement
# watermelon
# <class 'list'>
# ['sweet', 'round', 'green']




#Transfer dictionary

att1={'taste':'sweet','shape':'circular','color':'green'}
get3=melon('watermelon',att1)
print(get3)

#results of enforcement
# watermelon
# <class 'dict'>
# {'taste': 'sweet', 'shape': 'round', 'color': 'green'}

Problems after custom functions pass lists and dictionaries
Get the list passed from the parameter in the user-defined function. After the dictionary object, if their elements are changed inside the function, the elements that affect the variables before passing outside the function will be synchronized.

For example:

def Fruit(name,att):
    att[0]=att[0]*0.8
    return att

att_L=[20,'sweet','circular','green']  #Set 20 as the price
get1=Fruit('watermelon',att_L)  #Call the function to return the modified list

print(get1) #Print returned list objects
print(att_L)#Print original list objects

# Execution result:
# [16.0, 'sweet', 'round', 'green']  
# [16.0, 'sweet', 'round', 'green']  

After modifying the elements of the passed list object in the user-defined function body, here is the list object att outside the function body after modifying the price_ The value of L has also been modified synchronously. This may not be desirable.

In the function, the direct transfer of list objects leads to the synchronous change of list objects outside the function. It is proved that the transfer list (and Dictionary) actually transfers objects with the same address in memory. When the value of the incoming object is modified in the function body, the objects outside the function body will naturally change.

Solution: copy the list (Dictionary) object method to avoid

def Fruit(name,att):
    att[0]=att[0]*0.8
    return att

att_L=[20,'sweet','circular','green']  #Set 20 as the price

get2=Fruit('watermelon',att_L.copy())  #Using copy() method to copy objects
print(get2)
print(att_L)


# The implementation results are:
# [16.0, 'sweet', 'round', 'green']
# [20, 'sweet', 'round', 'green']

Function transfer object summary:
The objects passed can be divided into immutable objects and variable objects. Numbers, strings and tuples belong to immutable objects, while lists and dictionaries belong to variable objects.
Immutable object: if the value is modified in the function, it will become a new object (a new address will be generated in memory)
Variable object: when modifying the value in a function, it is the same object inside and outside the function, but the value changes synchronously.

Topics: Python Back-end