# Advanced learning of Day11 function in Python

Time：2020-9-14
1. The trap of default parameters (only for data types that are variable for default parameters): if the default parameter uses variable type data, the default parameter is the same (with the same ID) no matter how many times the default parameter is called. Variable data types of default parameters are neither global nor local, and will not disappear after definition (local name space will disappear).

``````def func(num,nums=[]):
nums.append(num)
return nums
ret1 = func(1)
print(ret)
>>>[1]
ret2 = fun(2)
print(ret2)
>>>[1,2] include the first data.

#For example:
def func(a,list=[]):
list.append(a)
return list
ret1 = func(10,)
print(ret1)         #[10]
Print (func (20, [])) # [20] # re pass in parameters for the list
print(func(100))    #[10,100]
print(ret1)         #[10,100]``````
2. The trap of local scope: in a function, if a variable is defined, but the variable is referenced before the variable is defined, an error will still be reported even if the global variable has this reference variable.

``````#Example 1:
count = 1
def func():
count += 1
print(count)
func()
IndentationError: unindent does not match any outer indentation level

#Example 2:
count = 1
def func():
print(count)
func()      #1

#Example 3:
count = 1
def func():
print(count)
count = 1
func()
UnboundLocalError: local variable 'count' referenced before assignment``````
3. global nonlocal

• global:1. Declare a global variable in the local scope.

``````#1.
num = 0
def func():
num = 1
print(num)    #0

#2.
def func():
global num
num = 1
Print (Num) ා will report an error.

#3.
def func():
global num
num = 1
func()
print(num)  #1

#3.
num = 0
def func():
global num
num = 1
func()
print(num)    #1``````
• Nonlocal: cannot operate on global variables; it is mainly used for modifying local variables of outer functions by inner functions.

``````def func1():
count = 1
def inner():
nonlocal count
count+=1
inner()``````
4. Application of function name

• The function name refers to theMemory address

• Function name + () can execute the function

``````#Example 1:
def func():
print(1)
f1 = func
f2 = f1
f2()     #1

#Example 2
def func1():
print(1)
def func2():
print(2)
func2 = func1
func2()    #1``````
• The function name can be used as an element of the container class data type

``````#Example 3:
def func1():
print(1)
def func2():
print(2)
def func3():
print(3)
l1 = [func1,func2,func3]
for i in l1:
i()   #1 2 3``````
• The function name can be used as an argument to the function

``````def func0(a):
print(1)
def func1(x):
x()
func1(func0)      #1``````
• The function name can be used as the return value of the function.

``````def func1():
print(1)
def func2(x):
return x
ret = func2(func)
ret()       #1``````
5. Formatted output (after version 3.6)

• Basic expression:
`````````python

name = 'python'
age = '18'
MSG = f'my name is {name}, this year {age} ා add a character f before the quotation mark

`````````

``````count = 2
Print (f 'final result: {count * * 2}')

name = 'python'
My name is{ name.upper ()}')

dic = {'name':'python','age':'18'}
MSG = f'my name is {DIC ["name"]}, this year {DIC ["age"]} 'ා pay attention to the use of double quotation marks and single quotation marks.

list = ['python','18']
MSG = f'my name is {list [0]}, this year {list [1]} '``````
• You can combine functions:

``````def sum1(a,b):
return a+b
Print (f 'the final result is {sum1 (1,2)}')``````
• Advantages: 1. 2. It can be used in combination with expression and function. 3. Higher efficiency

6. Iterator:

• Iteratable objects:

Object: everything in Python is an object. Iterative: can be carried outCycle updateA value of.

From a professional point of view, it contains`__iter__`Methods are iteratable objects. For example: STR, list, tuple, dict, set, range, file handle, etc.

• Gets all the methods of the object and presents them as strings: dir ()

``````s1 = 'qwer'
Print (dir (S1)) ා please test yourself.``````
• To determine whether an object is an iteratable object:

``````s1 = 'qwer'
print('__iter__' in dir(s1))  #True``````

1. The stored data can be directly displayed, more intuitive.
2. Have more methods, easy to operate.

1. Takes up memory.

2. It can’t be directly passed through the for loop (it can’t be directly valued), and python automatically converts it toiterator (see below) followed by a for loop (take values with the next () method, see below.).

``````l1 = [1,2,3,4]
for i in l1:
Print (I) ා Python automatically converts it to an iterator and then performs a for loop``````
• Iterator:

The definition of iterator: inner contains`__iter__`and`__next__`The object of a method is an iterator. For example: file handle.

• Determine whether it is an iterator:

``````with open ('1.txt',encoding='utf-8',mode='w') as f1:
print('__iter__' in dir(f1) and '__next__' in dir(f1))``````
• Iteratable objects can be converted to iterators:

``````s1 = 'qwert'
obj = iter(s1)
#Or:
s1.__iter__()
Print (obj) ා please self test, it will return the memory address of an iterator``````
• Value the iterator:

``````s1 = 'qwert'
obj = iter(s1)
Next (obj) ා takes the first element of the string S1
Next (obj) ා returns the second element of the string S1
#Or:
obj.__next__()``````

1. Save memory. The iterator occupies only one data space in memory, because each time the previous data is retrieved, it will be released in memory. The iterator has an inert mechanism. Next time, it takes only one value, never more.

• The disadvantages of iterators are as follows

1. You can’t directly view the data inside.

2. It can only be taken downward.

3. Slow.

• Comparison between iteratable objects and iterators

• The iteratable object is a data set with more operation methods, more intuitive and relatively less data storage (millions of data, 8g memory can bear).
• When the focus is on flexible data processing and enough memory space, the data can be set as an iterative object.
• Iterator is a data set that can save memory and record the value position. The value can be obtained by loop and next method, but it is not intuitive and the operation method is relatively single.
• When the amount of data is too large, you can choose to set the data as an iterator.
• Use while loop to simulate for loop to get values for iteratable objects: (please test yourself)

``````l1 = [1,2,3,4,5,6,7,8]
obj = iter(l1)
while 1:
Try: try: exception handling
print(next(obj))
except StopIteration:
break``````

## How to share queues with hypertools 2.5

Share queue with swote To realize asynchronous IO between processes, the general idea is to use redis queue. Based on the development of swote, the queue can also be realized through high-performance shared memory table. Copy the code from the HTTP tutorial on swoole’s official website, and configure four worker processes to simulate multiple producers […]