Imooc - Python3 入门教程: Python的函数

介绍Python代码最基本的抽象类型:函数,以及如何定义和调用函数
更新于: 2022-01-17 08:06:55

定义函数

# 标准写法
def my_abs(x):
    if x >= 0:
        return x
    else:
        return -x
# 更 if/else 的写法
def my_abs(x):
    if x >= 0: return x
    return -x
# 类3元表达式
def my_abs(x):
    return x if x >= 0 else -x

返回值

# 无返回
def list_sum(l):
    result = 0
    for num in l:
        result = result + num
    print('result is {}'.format(result))
    return
    
# 多个返回
def data_of_square(side):
    C = 4 * side
    S = side * side
    return C, S

C, S = data_of_square(16)
print('周长 = {}'.format(C)) # ==> 周长 = 64
print('面积 = {}'.format(S)) # ==> 面积 = 256    

函数的参数

  • 普通函数 
  • 可选参数函数
  • 可变参数函数
# 类型判断
isinstance(100, int) # ==> True
isinstance(100.0, int) # ==> False
isinstance('3.1415926', str) # ==> True

# 默认参数(optional 可选参数)
def power(x, n=2):
    s = 1
    while n > 0:
        n = n - 1
        s = s * x
    return s

# 可变参数
def average(*args):
    sum = 0
    for item in args:
        sum += item
    avg = sum / len(args)
    return avg        

# 又一个可变参数
def manyArgs(*arg):
    print("I was called with", len(arg), "arguments:", arg)

manyArgs(1, 2, 3, 4)
# I was called with 4 arguments: (1, 2, 3, 4)

# 可选参数(optional)
def print_student(student, grade="Fifth"):
	print("{} is in {} grade.".format(student, grade))

可变关键字参数

Python函数提供可变关键字参数,对于可变关键字参数,可以通过关键字的名字key找到对应的参数值,想想这和我们之前学习过的什么类似?是的没错,dict,Python会把可变关键字参数当作dict去处理;对于可变关键字参数,一般使用**kwargs来表示

def info(**kwargs):
    print(
        'name: {}, gender: {}, age: {}'.format(
            kwargs.get('name'),
            kwargs.get('gender'),
            kwargs.get('age'))
    )

info(name='Alice', gender='girl', age=16)

让 dict 类型以 点 方式去调用

class dotdict(dict):
    """dot.notation access to dictionary attributes"""
    __getattr__ = dict.get
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

def fun1(s1, s2, **kwargs):
    args = dotdict(kwargs)
    print(args)
    print(args["verbose"])
    # 精华在这一句
    print(args.verbose)

# call the args with dot function
fun1(1, 2, verbose=True)
{'verbose': True}
True
True

参考