函数

作者: 凯光V | 来源:发表于2021-07-27 08:59 被阅读0次

    函数

    定义:

    def add(x, y):
        return x + y
    
    print(add(1, 2))    
    

    空函数

    def add():
        pass
    

    参数检查

    def add(x, y):
        if not isinstance (x, int):
            raise TypeError('type error with x')
        if not isinstance(y, int):
            raise TypeError('type error with y')
        return x + y
    
    print(add('1', 2))    
    

    返回多个值

    def add(x, y):
        # return x, y, 3
        return (x, y, 3)
    
    x, y, z = add(1, 2)
    print(x, y, z) # 1, 2, 3
    

    默认参数

    def power(x, n = 2):
        s = 1
        while(n > 0):
            s = s * x
            n = n - 1
        return s
    
    print(power(2, 3))    
    

    默认参数必须为不变对象

    def add(l = []):
        l.append('end')
        return l
    
    rs = add()
    rs = add()
    print(rs) # ['end', 'end']
    

    需要改为

    def add(l = None):
        if l is None:
            l = []
        l.append('end')
        return l
    
    rs = add()
    rs = add()
    print(rs)    
    

    可变参数

    # 加 *
    def calc(*numbers):
        sum = 0
        for n in numbers:
            sum = sum + n
        return sum
    
    print(calc(1, 2, 3))
    

    将 list 转可变参数

    def calc(*numbers):
        sum = 0
        for n in numbers:
            sum = sum + n
        return sum
    
    list = [1, 2, 3]    
    print(calc(*list)) # 加 *
    

    关键字参数

    # kv 前加 **
    def person(name, age, **kv):
        return name, age, kv
    
    print(person('fedor', 20, city = 'beijng')) # ('fedor', 20, {'city': 'beijng'})
    

    将 dict 转可关键字参数

    def person(name, age, **kv):
        return name, age, kv
    
    map = { 'city': 'beijng', 'tel': '01093897477' }
    print(person('fedor', 20, **map)) # map 前加 **
    

    限制关键字参数名字:

    def person(name, age, *, city='Beijing', job):
        print(name, age, city, job)
    
    person('Jack', 24, job='Engineer') # Jack 24 Beijing Engineer
    person('Jack', 24, job='Engineer', tel = '01000000000') # TypeError: person() got an unexpected keyword argument 'tel'
    

    相关文章

      网友评论

          本文标题:函数

          本文链接:https://www.haomeiwen.com/subject/zpinmltx.html