博客
关于我
Python内置函数详解——总结篇
阅读量:798 次
发布时间:2023-03-08

本文共 10857 字,大约阅读时间需要 36 分钟。

Python 内置函数详解:功能与示例全解析

作为一个经常使用 Python 的开发者,了解内置函数的功能和用法是非常重要的。本文将对 Python 中的 68 个内置函数进行详细解析,帮助你快速掌握这些常用工具。

一、数学运算

1. abs

返回一个数值的绝对值。

>>> abs(-2)
2

2. divmod

返回两个数值的商和余数。

>>> divmod(5, 2)
(2, 1)
>>> divmod(5.5, 2)
(2.0, 1.5)

3. max

返回可迭代对象中的元素中的最大值或所有参数的最大值。

>>> max(1, 2, 3)
3
>>> max('1234')
'4'
>>> max(-1, 0)
0
>>> max(-1, 0, key=abs)
-1

4. min

返回可迭代对象中的元素中的最小值或所有参数的最小值。

>>> min(1, 2, 3)
1
>>> min('1234')
'1'
>>> min(-1, -2)
-2
>>> min(-1, -2, key=abs)
-1

5. pow

返回两个数值的幂运算值或其与指定整数的模值。

>>> pow(2, 3)
8
>>> pow(2, 3, 5)
2

6. round

对浮点数进行四舍五入求值。

>>> round(1.1314926, 1)
1.1
>>> round(1.1314926, 5)
1.13149

7. sum

对元素类型是数值的可迭代对象中的每个元素求和。

>>> sum((1, 2, 3, 4))
10
>>> sum((1.5, 2.5, 3.5, 4.5))
12.0
>>> sum((1, 2, 3, 4), -10)
0

二、类型转换

1. bool

根据传入的参数的逻辑值创建一个新的布尔值。

>>> bool()
False
>>> bool(0)
False
>>> bool(1)
True

2. int

根据传入的参数创建一个新的整数。

>>> int()
0
>>> int(3)
3
>>> int(3.6)
3

3. float

根据传入的参数创建一个新的浮点数。

>>> float()
0.0
>>> float(3)
3.0
>>> float('3')
3.0

4. complex

根据传入参数创建一个新的复数。

>>> complex()
0j
>>> complex('1+2j')
(1+2j)
>>> complex(1, 2)
(1+2j)

5. str

返回一个对象的字符串表现形式。

>>> str()
''
>>> str(None)
'None'
>>> str('abc')
'abc'
>>> str(123)
'123'

6. bytearray

根据传入的参数创建一个新的字节数组。

>>> bytearray('中文', 'utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'

7. bytes

根据传入的参数创建一个新的不可变字节数组。

>>> bytes('中文', 'utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'

8. memoryview

根据传入的参数创建一个新的内存查看对象。

>>> v = memoryview(b'abcefg')
>>> v[1]
98
>>> v[-1]
103

9. ord

返回Unicode字符对应的整数。

>>> ord('a')
97

10. chr

返回整数所对应的Unicode字符。

>>> chr(97)
'a'

11. bin

将整数转换成2进制字符串。

>>> bin(3)
'0b11'

12. oct

将整数转化成8进制数字符串。

>>> oct(10)
'0o12'

13. hex

将整数转换成16进制字符串。

>>> hex(15)
'0xf'

14. tuple

根据传入的参数创建一个新的元组。

>>> tuple()
()
>>> tuple('121')
('1', '2', '1')

15. list

根据传入的参数创建一个新的列表。

>>> list()
[]
>>> list('abcd')
['a', 'b', 'c', 'd']

16. dict

根据传入的参数创建一个新的字典。

>>> 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}

17. set

根据传入的参数创建一个新的集合。

>>> set()
set()
>>> a = set(range(10))
>>> a
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

18. frozenset

根据传入的参数创建一个新的不可变集合。

>>> a = frozenset(range(10))
>>> a
frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})

19. enumerate

根据可迭代对象创建枚举对象。

>>> 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')]

20. range

根据传入的参数创建一个新的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]

21. iter

根据传入的参数创建一个新的可迭代对象。

>>> 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

22. slice

根据传入的参数创建一个新的切片对象。

>>> c1 = slice(5)
>>> c1
slice(None, 5, None)
>>> c2 = slice(2, 5)
>>> c2
slice(2, 5, None)
>>> c3 = slice(1, 10, 3)
>>> c3
slice(1, 10, 3)

23. super

根据传入的参数创建一个新的子类和父类关系的代理对象。

# 定义父类 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__

24. object

创建一个新的 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'

三、序列操作

1. all

判断可迭代对象的每个元素是否都为True值。

>>> all([1, 2])
True
>>> all([0, 1, 2])
False
>>> all(())
True
>>> all({})
True

2. any

判断可迭代对象的元素是否有为True值的元素。

>>> any([0, 1, 2])
True
>>> any([0, 0])
False
>>> any([])
False
>>> any({})
False

3. filter

使用指定方法过滤可迭代对象的元素。

>>> a = list(range(1, 10))
>>> def if_odd(x):
... return x % 2 == 1
...
>>> list(filter(if_odd, a))
[1, 3, 5, 7, 9]

4. map

使用指定方法作用传入的每个可迭代对象的元素,生成新的可迭代对象。

>>> a = map(ord, 'abcd')
>>> a
>>> list(a)
[97, 98, 99, 100]

5. next

返回可迭代对象中的下一个元素值。

>>> 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

6. reversed

反转序列生成新的可迭代对象。

>>> a = reversed(range(10))
>>> a
>>> list(a)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

7. sorted

对可迭代对象进行排序,返回一个新的列表。

>>> 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']

8. zip

聚合传入的每个迭代器中相同位置的元素,返回一个新的元组类型迭代器。

>>> x = [1, 2, 3]
>>> y = [4, 5, 6, 7, 8]
>>> list(zip(x, y))
[(1, 4), (2, 5), (3, 6)]

四、对象操作

1. help

返回对象的帮助信息。

>>> help(str)
Help on class str in module builtins:
class str(object): ...

2. dir

返回对象或者当前作用域内的属性列表。

>>> import math
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', ...]

3. id

返回对象的唯一标识符。

>>> a = 'some text'
>>> id(a)
69228568

4. hash

获取对象的哈希值。

>>> hash('good good study')
1032709256

5. type

返回对象的类型,或者根据传入的参数创建一个新的类型。

>>> type(1)
>>> D = type('D', (A, B), dict(InfoD='some thing defined in D'))
>>> d = D()
>>> d.InfoD
'some thing defined in D'

6. len

返回对象的长度。

>>> 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

7. ascii

返回对象的可打印表字符串表现方式。

>>> ascii(1)
'1'
>>> ascii('&')
"'&'"
>>> ascii(9000000)
'9000000'
>>> ascii('中文')
"\\u4e2d\\u6587"

8. format

格式化显示值。

# 字符串格式化
>>> 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'

9. vars

返回当前作用域内的局部变量和其值组成的字典,或者返回对象的属性列表。

# 作用于类实例
>>> 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'}

五、反射操作

1. import

动态导入模块。

>>> index = __import__('index')
>>> index.sayHello()

2. isinstance

判断对象是否是类或者类型元组中任意类元素的实例。

>>> isinstance(1, int)
True
>>> isinstance(1, str)
False
>>> isinstance(1, (int, str))
True

3. issubclass

判断类是否是另外一个类或者类型元组中任意类元素的子类。

>>> issubclass(bool, int)
True
>>> issubclass(bool, str)
False
>>> issubclass(bool, (str, int))
True

4. hasattr

检查对象是否含有属性。

# 定义类 Student
>>> class Student:
... def __init__(self, name):
... self.name = name
...
>>> s = Student('Aim')
>>> hasattr(s, 'name')
True
>>> hasattr(s, 'age')
False

5. getattr

获取对象的属性值。

>>> 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'

6. setattr

设置对象的属性值。

>>> class Student:
... def __init__(self, name):
... self.name = name
...
>>> s = Student('Kim')
>>> setattr(s, 'name', 'Bob')
>>> s.name
'Bob'

7. delattr

删除对象的属性。

# 定义类 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.name
Traceback (most recent call last):
File "
", line 1, in
delattr(a, 'name')
AttributeError: can't delete attribute

8. callable

检测对象是否可被调用。

# 定义类 B
>>> class B:
... def __call__(self):
... print('instances are callable now.')
...
>>> callable(B)
True
>>> b = B()
>>> callable(b)
True
>>> b()
instances are callable now.

六、变量操作

1. globals

返回当前作用域内的全局变量和其值组成的字典。

>>> 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__':
}

2. locals

返回当前作用域内的局部变量和其值组成的字典。

>>> 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}

七、交互操作

1. print

向标准输出对象打印输出。

>>> print(1, 2, 3)
1 2 3
>>> print(1, 2, 3, sep='+')
1+2+3
>>> print(1, 2, 3, sep='+', end='=?')
1+2+3=?

2. input

读取用户输入值。

>>> s = input('please input your name:')
please input your name:Ain
>>> s
'Ain'

八、文件操作

1. open

使用指定的模式和编码打开文件,返回文件读写对象。

>>> a = open('test.txt', 'rt')
>>> a.read()
'some text'
>>> a.close()

九、编译执行

1. compile

将字符串编译为代码或者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

2. eval

执行动态表达式求值。

>>> eval('1+2+3+4')
10

3. exec

执行动态语句块。

>>> exec('a=1+2')
a: 3

4. repr

返回一个对象的字符串表现形式。

>>> a = 'some text'
>>> str(a)
'some text'
>>> repr(a)
"'some text'"

十、装饰器

1. property

标示属性的装饰器。

# 定义类 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.name
Traceback (most recent call last):
File "
", line 1, in
del c.name
AttributeError: can't delete attribute

2. classmethod

标示方法为类方法的装饰器。

# 定义类 C
>>> class C:
... @classmethod
... def f(cls, arg1):
... print(cls) # 类方法的第一个参数是类
... print(arg1)
...
>>> C.f('类对象调用类方法')
类对象调用类方法
>>> c = C()
>>> c.f('类实例对象调用类方法')
类实例对象调用类方法

3. staticmethod

标示方法为静态方法的装饰器。

# 使用装饰器定义静态方法
>>> 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/

你可能感兴趣的文章
python360百科_11月编程排行榜:Python超过Java成第二
查看>>
Python关于Paginator分页函数详细解析 附实战代码
查看>>
python3、ipython3、setup-tools、pip等环境搭建详细总结
查看>>
python3下使用cv2.imwrite存储带有中文路径图片或者绝对路径图片
查看>>
python3与django中@property详解
查看>>
python3中如何表示无穷大
查看>>
Python3中提示:no module named 'wxpy'
查看>>
python3中选择文件对话框的格式打开和保存图片
查看>>
python3为什么print永远都是地址_Python3 print 函数用法总结
查看>>
Python3之uuid模块
查看>>
Python3之写入Excel文档(xlsxwriter)
查看>>
Python3之打印操作打印流重定向(下)
查看>>
python3判断字典、列表、元组为空以及字典是否存在某个key的方法
查看>>
Python3利用pymysql操作 MySQL
查看>>
python3处理json文件中含有中文dumps的应用
查看>>
Python3子进程输出
查看>>
Python3学习笔记3,变量、运算符
查看>>
Python3学习笔记(urllib模块的使用)
查看>>
python3安装scapy_Linux下安装scapy-python3
查看>>
python3实现socket通信
查看>>