本文共 10857 字,大约阅读时间需要 36 分钟。
作为一个经常使用 Python 的开发者,了解内置函数的功能和用法是非常重要的。本文将对 Python 中的 68 个内置函数进行详细解析,帮助你快速掌握这些常用工具。
返回一个数值的绝对值。
>>> abs(-2)2
返回两个数值的商和余数。
>>> divmod(5, 2)(2, 1)>>> divmod(5.5, 2)(2.0, 1.5)
返回可迭代对象中的元素中的最大值或所有参数的最大值。
>>> max(1, 2, 3)3>>> max('1234')'4'>>> max(-1, 0)0>>> max(-1, 0, key=abs)-1 返回可迭代对象中的元素中的最小值或所有参数的最小值。
>>> min(1, 2, 3)1>>> min('1234')'1'>>> min(-1, -2)-2>>> min(-1, -2, key=abs)-1 返回两个数值的幂运算值或其与指定整数的模值。
>>> pow(2, 3)8>>> pow(2, 3, 5)2
对浮点数进行四舍五入求值。
>>> round(1.1314926, 1)1.1>>> round(1.1314926, 5)1.13149
对元素类型是数值的可迭代对象中的每个元素求和。
>>> sum((1, 2, 3, 4))10>>> sum((1.5, 2.5, 3.5, 4.5))12.0>>> sum((1, 2, 3, 4), -10)0
根据传入的参数的逻辑值创建一个新的布尔值。
>>> bool()False>>> bool(0)False>>> bool(1)True
根据传入的参数创建一个新的整数。
>>> int()0>>> int(3)3>>> int(3.6)3
根据传入的参数创建一个新的浮点数。
>>> float()0.0>>> float(3)3.0>>> float('3')3.0 根据传入参数创建一个新的复数。
>>> complex()0j>>> complex('1+2j')(1+2j)>>> complex(1, 2)(1+2j) 返回一个对象的字符串表现形式。
>>> str()''>>> str(None)'None'>>> str('abc')'abc'>>> str(123)'123' 根据传入的参数创建一个新的字节数组。
>>> bytearray('中文', 'utf-8')b'\xe4\xb8\xad\xe6\x96\x87' 根据传入的参数创建一个新的不可变字节数组。
>>> bytes('中文', 'utf-8')b'\xe4\xb8\xad\xe6\x96\x87' 根据传入的参数创建一个新的内存查看对象。
>>> v = memoryview(b'abcefg')>>> v[1]98>>> v[-1]103
返回Unicode字符对应的整数。
>>> ord('a')97 返回整数所对应的Unicode字符。
>>> chr(97)'a'
将整数转换成2进制字符串。
>>> bin(3)'0b11'
将整数转化成8进制数字符串。
>>> oct(10)'0o12'
将整数转换成16进制字符串。
>>> hex(15)'0xf'
根据传入的参数创建一个新的元组。
>>> tuple()()>>> tuple('121')('1', '2', '1') 根据传入的参数创建一个新的列表。
>>> list()[]>>> list('abcd')['a', 'b', 'c', 'd'] 根据传入的参数创建一个新的字典。
>>> dict(){}>>> dict(a=1, b=2){'b': 2, 'a': 1}>>> dict(zip(['a', 'b'], [1, 2])){'b': 2, 'a': 1}>>> dict((('a', 1), ('b', 2))){'b': 2, 'a': 1} 根据传入的参数创建一个新的集合。
>>> set()set()>>> a = set(range(10))>>> a{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} 根据传入的参数创建一个新的不可变集合。
>>> a = frozenset(range(10))>>> afrozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9}) 根据可迭代对象创建枚举对象。
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']>>> list(enumerate(seasons))[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]>>> list(enumerate(seasons, start=1))[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
根据传入的参数创建一个新的range对象。
>>> a = range(10)>>> b = range(1, 10)>>> c = range(1, 10, 3)>>> a, b, c(range(0, 10), range(1, 10), range(1, 10, 3))>>> list(a), list(b), list(c)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 4, 7]
根据传入的参数创建一个新的可迭代对象。
>>> a = iter('abcd')>>> a >>> next(a)'a'>>> next(a)'b'>>> next(a)'c'>>> next(a)'d'>>> next(a)Traceback (most recent call last): File " ", line 1, in next(a)StopIteration 根据传入的参数创建一个新的切片对象。
>>> c1 = slice(5)>>> c1slice(None, 5, None)>>> c2 = slice(2, 5)>>> c2slice(2, 5, None)>>> c3 = slice(1, 10, 3)>>> c3slice(1, 10, 3)
根据传入的参数创建一个新的子类和父类关系的代理对象。
# 定义父类 A>>> class A(object):... def __init__(self):... print('A.__init__')...# 定义子类 B,继承 A>>> class B(A):... def __init__(self):... print('B.__init__')... super().__init__()...# 创建 B 实例>>> b = B()>>> b.__init__B.__init__A.__init__ 创建一个新的 object 对象。
>>> a = object()>>> a.name = 'kim'Traceback (most recent call last): File "", line 1, in a.name = 'kim'AttributeError: 'object' object has no attribute 'name'
判断可迭代对象的每个元素是否都为True值。
>>> all([1, 2])True>>> all([0, 1, 2])False>>> all(())True>>> all({})True 判断可迭代对象的元素是否有为True值的元素。
>>> any([0, 1, 2])True>>> any([0, 0])False>>> any([])False>>> any({})False 使用指定方法过滤可迭代对象的元素。
>>> a = list(range(1, 10))>>> def if_odd(x):... return x % 2 == 1...>>> list(filter(if_odd, a))[1, 3, 5, 7, 9]
使用指定方法作用传入的每个可迭代对象的元素,生成新的可迭代对象。
>>> a = map(ord, 'abcd')>>> a
返回可迭代对象中的下一个元素值。
>>> a = iter('abcd')>>> next(a)'a'>>> next(a)'b'>>> next(a)'c'>>> next(a)'d'>>> next(a)Traceback (most recent call last): File " ", line 1, in next(a)StopIteration 反转序列生成新的可迭代对象。
>>> a = reversed(range(10))>>> a>>> list(a)[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
对可迭代对象进行排序,返回一个新的列表。
>>> a = ['a', 'b', 'd', 'c', 'B', 'A']>>> sorted(a)['A', 'B', 'a', 'b', 'c', 'd']>>> sorted(a, key=str.lower)['a', 'A', 'b', 'B', 'c', 'd']
聚合传入的每个迭代器中相同位置的元素,返回一个新的元组类型迭代器。
>>> x = [1, 2, 3]>>> y = [4, 5, 6, 7, 8]>>> list(zip(x, y))[(1, 4), (2, 5), (3, 6)]
返回对象的帮助信息。
>>> help(str)Help on class str in module builtins:class str(object): ...
返回对象或者当前作用域内的属性列表。
>>> import math>>> dir(math)['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', ...]
返回对象的唯一标识符。
>>> a = 'some text'>>> id(a)69228568
获取对象的哈希值。
>>> hash('good good study')1032709256 返回对象的类型,或者根据传入的参数创建一个新的类型。
>>> type(1)>>> D = type('D', (A, B), dict(InfoD='some thing defined in D'))>>> d = D()>>> d.InfoD'some thing defined in D'
返回对象的长度。
>>> len('abcd')4>>> len(bytes('abcd', 'utf-8'))4>>> len((1, 2, 3, 4))4>>> len([1, 2, 3, 4])4>>> len(range(1, 5))4>>> len({'a': 1, 'b': 2, 'c': 3, 'd': 4})4>>> len(frozenset('abcd'))4 返回对象的可打印表字符串表现方式。
>>> ascii(1)'1'>>> ascii('&')"'&'">>> ascii(9000000)'9000000'>>> ascii('中文')"\\u4e2d\\u6587" 格式化显示值。
# 字符串格式化>>> format('some string', 's')'some string'>>> format(3, 'b')'11'>>> format(97, 'c')'a'>>> format(11, 'd')'11'>>> format(11, 'o')'13'>>> format(11, 'x')'b'>>> format(11, 'X')'B'>>> format(11, 'n')'11'>>> format(0.00003141566, 'e')'3.141593e+08'>>> format(0.00003141566, '0.2e')'3.14e+08'>>> format(0.00003141566, '0.2E')'3.14E+08'>>> format(3.1415926777, '0.1g')'3'>>> format(3.1415926777, '0.2g')'3.1'>>> format(3.1415926777, '0.3g')'3.14'>>> format(3.1415926777, '0.10g')'3.14' 返回当前作用域内的局部变量和其值组成的字典,或者返回对象的属性列表。
# 作用于类实例>>> class A(object):... def __init__(self, name):... self.name = name...>>> a = A()>>> a.__dict__{}>>> a.name = 'Kim'>>> a.__dict__{'name': 'Kim'}>>> vars(a){'name': 'Kim'} 动态导入模块。
>>> index = __import__('index')>>> index.sayHello() 判断对象是否是类或者类型元组中任意类元素的实例。
>>> isinstance(1, int)True>>> isinstance(1, str)False>>> isinstance(1, (int, str))True
判断类是否是另外一个类或者类型元组中任意类元素的子类。
>>> issubclass(bool, int)True>>> issubclass(bool, str)False>>> issubclass(bool, (str, int))True
检查对象是否含有属性。
# 定义类 Student>>> class Student:... def __init__(self, name):... self.name = name...>>> s = Student('Aim')>>> hasattr(s, 'name')True>>> hasattr(s, 'age')False 获取对象的属性值。
>>> class Student:... def __init__(self, name):... self.name = name...>>> s = Student('Kim')>>> getattr(s, 'name')'Kim'>>> getattr(s, 'age', 6)6>>> getattr(s, 'age')Traceback (most recent call last): File " ", line 1, in getattr(s, 'age')AttributeError: 'Student' object has no attribute 'age' 设置对象的属性值。
>>> class Student:... def __init__(self, name):... self.name = name...>>> s = Student('Kim')>>> setattr(s, 'name', 'Bob')>>> s.name'Bob' 删除对象的属性。
# 定义类 A>>> class A:... def __init__(self, name):... self.name = name... def sayHello(self):... print('hello', self.name)...>>> a = A()>>> a.name'small'>>> delattr(a, 'name')>>> a.nameTraceback (most recent call last): File " ", line 1, in delattr(a, 'name')AttributeError: can't delete attribute 检测对象是否可被调用。
# 定义类 B>>> class B:... def __call__(self):... print('instances are callable now.')...>>> callable(B)True>>> b = B()>>> callable(b)True>>> b()instances are callable now. 返回当前作用域内的全局变量和其值组成的字典。
>>> globals(){'__spec__': None, '__package__': None, '__builtins__': , '__name__': '__main__', '__doc__': None, '__loader__': }>>> a = 1>>> globals(){'__spec__': None, '__package__': None, '__builtins__': , 'a': 1, '__name__': '__main__', '__doc__': None, '__loader__': } 返回当前作用域内的局部变量和其值组成的字典。
>>> def f():... print('before define a')... print(locals())... a = 1... print('after define a')... print(locals())...>>> f()before define a {}after define a {'a': 1} 向标准输出对象打印输出。
>>> print(1, 2, 3)1 2 3>>> print(1, 2, 3, sep='+')1+2+3>>> print(1, 2, 3, sep='+', end='=?')1+2+3=?
读取用户输入值。
>>> s = input('please input your name:')please input your name:Ain>>> s'Ain' 使用指定的模式和编码打开文件,返回文件读写对象。
>>> a = open('test.txt', 'rt')>>> a.read()'some text'>>> a.close() 将字符串编译为代码或者AST对象,使之能够通过exec语句来执行或者eval进行求值。
>>> code1 = 'for i in range(0, 10): print(i)'>>> compile1 = compile(code1, '', 'exec')>>> exec(compile1)0123456789>>> code2 = '1 + 2 + 3 + 4'>>> compile2 = compile(code2, '', 'eval')>>> eval(compile2)10
执行动态表达式求值。
>>> eval('1+2+3+4')10 执行动态语句块。
>>> exec('a=1+2')a: 3 返回一个对象的字符串表现形式。
>>> a = 'some text'>>> str(a)'some text'>>> repr(a)"'some text'"
标示属性的装饰器。
# 定义类 C>>> class C:... def __init__(self):... self._name = ''... @property... def name(self):... """i'm the 'name' property."""... return self._name... @name.setter... def name(self, value):... if value is None:... raise RuntimeError('name can not be None')... else:... self._name = value...>>> c = C()>>> c.name''>>> c.name = 'Kim'>>> c.name'Kim'>>> del c.nameTraceback (most recent call last): File " ", line 1, in del c.nameAttributeError: can't delete attribute 标示方法为类方法的装饰器。
# 定义类 C>>> class C:... @classmethod... def f(cls, arg1):... print(cls) # 类方法的第一个参数是类... print(arg1)...>>> C.f('类对象调用类方法') 类对象调用类方法>>> c = C()>>> c.f('类实例对象调用类方法') 类实例对象调用类方法 标示方法为静态方法的装饰器。
# 使用装饰器定义静态方法>>> class Student(object):... def __init__(self, name):... self.name = name... @staticmethod... def sayHello(lang):... print(lang)... if lang == 'en':... print('Welcome!')... else:... print('你好!')...>>> Student.sayHello('en')Welcome!>>> b = Student('Kim')>>> b.sayHello('zh')你好 通过以上详细解析,希望你能对 Python 内置函数有更深入的理解。如果有任何疑问或需要进一步的帮助,欢迎在评论区留言!
转载地址:http://fklfk.baihongyu.com/