Getting function

function

Introduced

What is the function?

Function is a tool that can be reused

Why use functions?

Prevent the readability of the code redundancy and enhanced code

How to use the function?

After the first use of defined

Specification defined function

def 函数名(参数1,参数2...):
    '''文档描述'''
    函数体
    return 值
#主要由关键字def+函数名(尽量为有意义的)+():组成

def: keyword-defined functions

Function name: function name memory function points to address, is the function body code reference. General function meaningful, can reflect the performance function

Function name: the name of the variable naming conventions and consistent naming convention
1, must not conflict with the keyword
2, be sure to see the name EENOW

Parentheses: brackets custom parameter, the parameter is optional, and need not specify the type of parameter

Colon: after the brackets to add a colon, and then start the next line indented writing code for the function body

Document Description: Description document function function, parameter description and other information, non-essential, but recommended together to enhance the readability of the function

Function body: the composition of the statements and expressions

return: return value of the function is defined, optional

Type function

No-argument function

def login(): #括号里面无参数
    print('登陆成功')

There are function parameters

username = input('请输入你的用户名:')
def login(username):
    print(username)

Empty function

def login():  #一般常用在编写多功能程序时构建项目框架,用pass充当函数体占位符
    pass

Call functions and function return values

Syntax used to detect only the function call into the definition phase and phase-defined function, the code does not execute the function body

Do not write return

#不写return默认返回None
def login():
    print('success')


print(login())
#结果为
success
None

Write return only: Only an end to the role of the function body code, default return None

Write return None: Write only return with the same effect

return return a value: The result can be returned to use as a variable

return return multiple values: a plurality of the returned values ​​into a tuple

2 The return value not want to be modified

3 can specify the data type returned

Types of actual parameter Introduction

Parameter i.e. parameter defining a function, the statement in parentheses. It is essentially a parameter variable name, for receiving the transmitted external value.

That argument when calling the function, the incoming values ​​in parentheses, the value may be a combination of constants, variables, expressions, or three, essentially a variable argument value

PS: There are parameters in the calling function, the argument (value) will be assigned to the parameter (variable names). In Python, variable names and values ​​simply binding relationship, and for a function, this only takes effect when the binding relationship between function calls, released at the end of the call.

Parameter passing mode function

Positional parameters: parameters according to the parameter passing position
def register(name, age, sex):  # 定义位置形参:name,age,sex,三者都必须被传值           print('Name:%s Age:%s Sex:%s' % (name, age, sex))
    
    
register('sean', 66, 'boy')  #按照从左往右的先后顺序将值传给对应的参数
#输出结果为
Name:sean Age:66 Sex:boy
Keyword arguments: specify parameters by value, regardless of the location parameters
def register(name, age, sex):
    print(f'Name:{name}, Age:{age}, Sex:{sex}')


register(age=73, name='tank', sex='male')
#输出结果为
Name:tank, Age:73, Sex:male

PS: Note that when calling the function, when arguments also be used by mixing or keyword location, but must ensure a keyword parameter rear position parameters, may be repeated without assignment to a parameter

def register(name, age, sex):
    print('Name:{1},Age:{0}, Sex:{2}'.format(age, name, sex))


register(age=73, name='sean', sex='male')
register(sex='male', 18, name='sean')
register('tank', sex='male', age=18, name='sean')
#输出结果为
Name:sean,Age:73, Sex:male
SyntaxError: positional argument follows keyword argument
TypeError: register() got multiple values for argument 'name' 

The default parameters

def register(name, age, sex='male'):
    print('名字:{}, 年龄:{}, 性别:{}'.format(name,age,sex))


register('sean', 27) 
register('tank', 73, sex='female')
#输出结果为
名字:sean, 年龄:27, 性别:male  #这里我们在定义函数时,就设置了默认参数sex='male'
名字:tank, 年龄:73, 性别:female #因为我们自己设定了传参的值

#PS:
#    默认参数必须在位置参数之后
#    默认参数的值仅在函数定义阶段被赋值一次
#    如果在实参的时候传入了一个新的参数,就会使用新参数
#    默认参数在传值时,不要将可变类型当作参数传递
    
#每次调用都是在上一次的基础上向同一列表增加值
def foo(n,arg=None):
    if arg is None:
        arg = []
        arg.append(n)
        print(arg)
foo(1)
foo(2)
foo(3)
#输出结果为
[1]
[2]
[3]

Vararg

Variable-length positional parameters

#如果在最后一个形参名前加*号,那么在调用函数时,溢出的位置实参,都会被接收,以元组的形式保存下来赋值给该形参
#   *args:接受所有溢出的位置参数;接受的值都被存入一个元组
def foo(a, b, c, *args):
    print(a, b, c, *args)  #这里写为*args的话相当于直接将其当成一个正常的参数来用;也可以理解为*将默认得到的元组拆分了
    print(a, b, c, args)   

foo(1, 2, 3, [4, 5, 6])
#输出结果为
1 2 3 [4, 5, 6]
1 2 3 ([4, 5, 6],)   #默认将溢出的值存入一个元组


def foo(a, b, c, *args):
    print(a, b, c, args)
    print(a, b, c, *args)


foo(1, 2, 3, 4, 5, 6)
#输出结果为
1 2 3 (4, 5, 6)
1 2 3 4 5 6
#PS:两个对比我们可以得到,*号的作用打散你传入的容器类型


#求和小练习
def sum(*args):
    a = 0
    for i in args:
        a += i
    print(a)
    

sum(10, 11, 12)  

Variable-length keyword arguments

#如果在最后一个形参名前加**,那么在调用函数时,溢出的关键字参数,都会被接收,以字典的形式保存下来赋值给该形参
def foo(a, **kwargs):  #在最后一个参数kwargs前加**
    print(a, kwargs)
    print(a, *kwargs)

foo(b=1, a=2, c=3)    #溢出的关键字实参b=1,c=3都被**接收,以字典的形式保存下来,赋值给kwargs
#输出的结果为
2 {'b': 1, 'c': 3}
2 b c                #字典打散则取key


def foo(x, y, **kwargs):
    print(x, y, kwargs)
    
    
dic = {'a':1, 'b':2}
foo(1, 2, **dic)
#输出结果为
1 2 {'a': 1, 'b': 2}
#PS:
#实参可以直接定义字典传值给形参
#形参为常规参数时,实参可以是**的形式

Named keyword arguments

After defining ** kwargs parameters, function the caller can pass any keyword arguments key = value, if the function body execute code need to rely on a key, must be judged within the function

def register(name,age,**kwargs):
    if 'sex' in kwargs:  #有sex参数
        print('...')
    if 'height' in kwargs:
        print('***')     #有height参数


register('sean', 18, sex = 'male')
#输出结果为
...

Defines the caller wants to be transmitted in the form of a function key = value value, Python3 provides special syntax: ** required when defining parameter, used as a delimiter *, asterisk-shaped after the designated key parameter called ** word parameters. For these parameters, the function call, must be in the form of key = value of their traditional values, and the value must be delivered

def register(name,age,*,sex,height): #sex,height为命名关键字参数
    pass


register('lili',18,sex='male',height='1.8m') #正确使用

#命名关键字参数可以有默认值
def register(name,age,*,sex='male',height):
    print('Name:{},Age:{},Sex:{},Height:{}' .format(name, age, sex, height))


register('tank', 18, height='1.8m') #这里我们没有传入sex的参数
#输出的结果为
#需要强调的是:sex不是默认参数,height也不是位置参数,因为二者均在*后,所以都是命名关键字参数,形参sex=’male’属于命名关键字参数的默认值,因而即便是放到形参height之前也不会有问题。另外,如果形参中已经有一个args了,命名关键字参数就不再需要一个单独的*作为分隔符号了

def index(name, age, *args, sex = 'male', height):
    print(f'Name:{name}, Age:{age}, Args:{args}, Sex:{sex}, Height:{height}')


index('sean', 18, 1, 2, 3, height='170')
#输出结果为
Name:sean, Age:18, Args:(1, 2, 3), Sex:male, Height:180
To sum up all parameters can be used in any combination, but the order must be defined: positional parameters, default parameters, * args, named keyword arguments, ** kwargs
Keyword variable parameter * args parameter ** kwargs usually used in combination, if the parameter is a function of shape and ** kwargs * args, then on behalf of the function can be received in any form, of any length parameters
def func(x,y,z):
    print(x,y,z)
def index(*args,**kwargs):
    func(*args, **kwargs)


index(x=1,y=2,z=3)  #这里传的值可以是全为关键字参数或全为位置参数,或者混合使用
#该函数执行的大概流程为定义函数func和index,然后调用函数index,而函数index中的代码块为执行func函数,()中的参数*args和**kwargs即为上面要输出的x,y,z

According to the above wording, when the wrapper as a function of mass participation, in fact, follow the rules of the parameters of function func, call the function wrapper procedure is as follows:

  1. Position * 1 is received argument, preserved in the form of tuples, assigned to args, i.e. args = (1,), Keyword argument z = 3, y = 2 ** are received, saved in the form of a dictionary , assigned to kwargs, i.e. kwargs = { 'y': 2, 'z': 3}
  2. Performing FUNC ( args, kwargs), i.e. func (* (1,), ** { 'y': 2, 'z': 3}), is equivalent to func (1, z = 3, y = 2)

Tip: * args, ** kwargs the args and kwargs not be replaced by other names syntax errors, but using args

Guess you like

Origin www.cnblogs.com/a736659557/p/11892349.html