# 函数 将函数视为对象处理,函数满足一等对象的性质。 - 在运行时创建 - 能赋值给变量或数据结构中的元素 - 能作为参数传递给函数 - 能作为函数的返回结果 接受函数作为参数或将函数作为返回值的函数即为高等函数。 # dir ```python dir(obj) """ 列出对象obj的属性和方法 """ ``` # type ```python type(obj) """ 获取对象的数据类型 """ ``` # isinstance ```python isinstance(obj, typename) """ obj对象是否是typename类型 """ ``` # sorted ```python sorted(iterable, key=None, reverse=False) """ 参数 iterable: 可迭代对象 key: 单参数函数名 reverse: 是否降序 返回值 包含所有元素的排序的新列表 """ fuirts = ['strawberry', 'apple', 'cherry', 'raspberry', 'banana'] sorted(fruits, key=len) ``` # reversed ```python reversed(sequence) """ 接受一个可迭代序列 逆向 输出迭代器 """ ``` # map ```python map(func, *iterables) """ 参数 func: 对每个元素映射的函数 iterables: 可迭代的对象 返回一个生成器 """ ``` # filter ```python filter(function or None, iterable) """ 参数 function: 过滤函数 iterable: 可迭代对象 返回值 生成器 """ ``` # lambda ```python #lambda创建匿名函数 lambda x: x*x ``` # callable ```python callable(obj) """ 判断对象obj是否为可调用对象,返回True/False """ #自定义可调用对象 import random class BingoCage(): def __init__(self, items): self._items = list(items) random.shuffle(self._items) def pick(self): try: return self._items.pop() except IndexError: raise LookupError('Pick from empty BingoCage') def __call__(self): return self.pick() bingo = BingoCage(range(3)) bingo.pick() ``` # chr ```python chr(ascii_code) """ 输入一个ASCII码,输出对应的字符 ASCII码的范围为一个字节大小,[0, 255] """ chr(65) 'A' ``` # ord ```python ord(char) """ 输入一个字符,输出该字符对应的ASCII码 """ ord('W') 87 ``` # zip ```python zip(*iterables) """ zip函数接受输入若干可迭代对象,输出生成一个由元组构成的生成器,元组中的元素来自参数传入的各个可迭代对象 """ ``` # all ```python all(*iterables) """ 输入的可迭代对象是否全为True,全True返回True;如果有一个为False,则返回False """ all([1, 2, 3]) True ``` # any ```python any(*iterables) """ 输入的可迭代对象是否全部为False,全False返回False;如果有一个为True,则返回True """ any([None, None]) False ``` # round ```python round(number, ndigits=None) """ 输入一个浮点数对象,规定四舍五入的位数ndigits 返回一个四舍五入的对象 如果不指定ndigits,那么返回一个对象 """ ```