07.函数

# 函数
def fun1():
    print(123)


fun1() # 123

参数:

# 参数
def fun2(obj):
    print(obj)
    obj += obj

参数传递:

# 传递不可变类型的代表值传递
str1 = 'abc'
print(str1)  # abc
fun2(str1)  # abc
print(str1)  # abc
# 传递可变类型的代表引用传递
list1 = ['a', 'b', 'c']
print(list1)  # ['a', 'b', 'c']
fun2(list1)  # ['a', 'b', 'c']
print(list1)  # ['a', 'b', 'c', 'a', 'b', 'c']

关键字参数:

# 关键字参数
fun2(obj=12)  # 12

为参数设置默认值:

# 为参数设置默认值
def fun3(obj, p='123'):
    print(str(obj) + p)


fun3(12)  # 12123
# 显示fun3()函数的默认值参数的当前值
print(fun3.__defaults__)  # ('123',)

可变参数:

# 可变参数
# 一种是*args,另一种是**kwargs
# *args:表示接收任意多个实际参数并将其放到一个元组中

def printi(*args):
    print(args, type(args))


printi('a')  # ('a',) <class 'tuple'>
printi('a', 'b', 'c', 'd')  # ('a', 'b', 'c', 'd') <class 'tuple'>
# 如果使用一个已经存在的列表作为可变参数,在字典名称前加*
list11 = ['a', 'b', 'c', 'd']
printi(*list11)  # ('a', 'b', 'c', 'd') <class 'tuple'>


# **kwargs:表示接收任意多个类似关键字参数一样显示赋值的实际参数,并将放到一个字典中

def printii(**kwargs):
    print(kwargs, type(kwargs))


printii(a='A', )  # {'a': 'A'} <class 'dict'>
printii(a='A', b='B', c='C', d='D')  # {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'} <class 'dict'>

# 如果使用一个已经存在的字典作为可变参数,在字典名称前加**
dict1 = {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}
printii(**dict1)  # {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'} <class 'dict'>

返回值:

# 返回值
def fun1():
    return 123


print(fun1())  # 123

变量的作用域:

# 变量的作用域
msg_g = 'hi' #  全局变量


def fun1():
    msg = 'hello'  # 局部变量msg
    print(msg)  # hello
    print(msg_g)  # hi


fun1()
# print(msg)#NameError: name 'msg' is not defined
print(msg_g)  # hi

匿名函数(lambda):

# 匿名函数(lambda)
# res = lambda[arg1,]:exp
# res:用于调用lambda表达式
# [arg1,]:可选参数,指定参数列表,多个参数间用,分割
# exp:必选参数,用于指定一个实现具体功能的表达式
import math
# 计算圆的面积
res = lambda r: math.pi * r * r
print(res(10))  # 314.1592653589793

猜你喜欢

转载自www.cnblogs.com/fly-book/p/11737031.html