Python编程——函数

文章目录

基础函数

help(函数名) 查看函数的帮助信息

使用isinstance()进行数据类型检查

if not isinstance(x, (int, float)):
    raise TypeError('bad operand type')

使用callable()判断对象能否被调用

callable([1, 2, 3]) # False

可变参数:在函数调用时自动组装为一个tuple

def calc(*numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum
​
calc(1, 2)
calc(1, 3, 5, 7)

*nums表示把nums这个list的所有元素作为可变参数传进去

nums = [1, 2, 3]
calc(*nums)

关键字参数:传入任意个含参数名的参数,在函数内部自动组装为一个dict

def person(**kw):
    print(kw)
    
person(city='Beijing') # {'city': 'Beijing'}
person(gender='M', job='Engineer') # {'gender': 'M', 'job': 'Engineer'}

命名关键字参数:限制关键字参数的名字,命名关键字参数必须传入参数名。

命名关键字参数需要一个特殊分隔符后面的参数被视为命名关键字参数。

def person(name, age, *, city, job):
    print(name, age, city, job)
    
def person(name, age, *args, city, job):
    print(name, age, args, city, job)
    
person('Jack', 24, job='Engineer')
# Jack 24 Beijing Engineer

参数定义的顺序:必选参数、默认参数、可变参数、命名关键字参数和关键字参数。

def f1(a, b, c=0, *args, **kw):
    print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)

高阶函数

可以接受函数作为参数的函数

def add(x, y, f):
    return f(x) + f(y)
​
add(-5, 6, abs)

map/reduce

map(function,Iterable) 返回迭代器

def f(x):
    return x * x
​
map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])

reduce(function,Iterable)

其中function接收两个参数,reduce把结果与序列的下一个继续做计算

from functools import reduce
def fn(x, y):
    return x * 10 + y
​
reduce(fn, [1, 3, 5, 7, 9])
# 13569

filter

用于过滤序列

def is_odd(n):
    return n % 2 == 1
​
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# filter返回Iterator

sorted

sorted(list,key,reverse=False) 从小到大排序

key为自定义排序函数,如key=abs, key=str.lower

函数作为返回值

闭包程序结构

返回函数不要引用任何循环变量,或者后续会发生变化的变量

def lazy_sum(*args):
    def sum():
        ax = 0
        for n in args:
            ax = ax + n
        return ax
    return sum
 f = lazy_sum(1, 3, 5, 7, 9)
 f() # 执行

匿名函数

lambda 参数:表达式

表达式为返回值

装饰器

在代码运行期间动态增加功能的方式

import functools
# 在函数调用前后自动打印日志,但又不希望修改now()函数的定义
def log(func):
    @functools.wraps(func) # 把原始函数的__name__等属性复制到wrapper()函数中
    def wrapper(*args, **kw):
        print('call',func.__name__) # 打印日志
        return func(*args, **kw) # 调用原函数
    return wrapper
    
@log # 把@log放到now()函数的定义处,相当于执行了语句now = log(now)
def now():
    print('function:now')

decorator本身需要传入参数

import functools
def log(text):
    def decorator(func):
        @functools.wraps(func) # 把原始函数的__name__等属性复制到wrapper()函数中
        def wrapper(*args, **kw):
            print(text, func.__name__)
            return func(*args, **kw)
        return wrapper
    return decorator
    
@log('execute')
def now():
    print('2015-3-25')

偏函数

functools.partial()

把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数

import functools
int2 = functools.partial(int, base=2)
int('1000000',2) # 按二进制转化为int
int2('1000000')

Python内置函数

staticmethod

返回函数的静态方法(静态方法可以不需要实例化)

class c():
    @staticmethod
    def f():
        pass
​
# 无需实例化调用
c.f()
​
# 实例化调用
c = C()
c.f()

发表评论