A function parameters
3. universal parameters
*args
When the function definition, * represents the polymerization, all of the positional parameters will be aggregated into one tuple, assigned to the args
def fun_name(*args):
print('%s, %s, %s, %s' % args)
fun_name('jason', 'carly', 'dog', 'cat')
Exercise: write the product of a function to calculate the numbers of all incoming function
def func(*args):
result = 1
for i in args:
result = i * result
return result
print(func(1, 2, 3, 4))
** kwargse
When the function is defined, ** it represents the aggregation of all keyword arguments will be aggregated into a dictionary, assigned to the kwargs
def info(**kwargs):
print(kwargs)
info(name='jason', age=24, sex='man')
# 万能参数
def info(*args, **kwargs):
print(args)
print(kwargs)
Shape parameters of the sequence:
def func(位置参数,*args,默认参数,仅限关键字参数,**kwargs):
# 默认参数和仅限关键字参数顺序可互换
When the function call, * on behalf of beaten
- Iterables only when broken up
- Corresponds to the actual effect for each loop iteration objects can be passed, the obtained results to pass the loop * args
def func(*args):
print(args)
func(*'1234', *'5678') #结果为('1', '2', '3', '4', '5', '6', '7', '8')
def func(*args):
print(args)
func(*[1, 2, 3, 4], *[5, 6, 7, 8]) # 结果为(1, 2, 3, 4, 5, 6, 7, 8)
def func(*args):
print(args)
func(*{'k1': 'v1', 'k2': 'v2'}, *{'k3': 'v3', 'k4': 'v4'})
# 结果为('k1', 'k2', 'k3', 'k4')
** with only scattered dictionary
- The actual effect is equivalent for each cycle passed a dictionary, but the key is that all kwargs cycle to get a dictionary consisting of
def func(**kwargs):
print(kwargs)
func(**{'k1': 'v1', 'k2': 'v2'}, **{'k3': 'v3', 'k4': 'v4'})
# 结果为{'k1': 'v1', 'k2': 'v2', 'k3': 'v3', 'k4': 'v4'}
* Other uses
# 首先看下分别赋值
a, b = (1, 2)
print(a, b) # 1 2
# 其实还可以这么用:
a, *b = (1, 2, 3, 4,)
print(a, b) # 1 [2, 3, 4]
*rest, a, b = range(5)
print(rest, a, b) # [0, 1, 2] 3 4
print([1, 2, *[3, 4, 5]]) # [1, 2, 3, 4, 5]
Second, the name space
-
Global namespace -> py us directly in the document, the variable declared outside the function belong to the global namespace
-
Local namespace -> variables declared in a function will be kept in the local namespace
-
Built-in namespace -> storage python interpreter provides us with the name, list, tuple, str, int these are built namespaces
Loading order: Built namespace -> local namespace -> Global Namespace
value sequence: global namespace -> local namespace -> Built namespace
Third, the scope
Globally scope: built-in namespace, global namespace
2. Local Scope: local namespace
- The local scope can refer to variables with global scope
- Global scope can not reference variables local scope
- Local scope can not change the variable with global scope
Global () Local ()
a = 1
b = 2
def func():
c = 3
d = 4
print(globals())
print(locals())
func()
Fourth, higher-order functions
def func1():
print(1)
def fun2():
print(2)
print(3)
fun2()
print(4)
func1()
"""结果为:
1
2
3
4
"""