Python 3 提供了一系列强大的内置函数,用于处理常见的编程任务。这些内置函数无需额外导入模块即可直接使用。了解和掌握这些内置函数可以提高代码的效率和可读性。本文将详细介绍 Python 3 的内置函数,包括其用法和示例。
一、常用内置函数
1. abs()
返回数字的绝对值。
print(abs(-5)) # 输出 5
print(abs(3.14)) # 输出 3.14
2. all()
如果 iterable 的所有元素都为 True(或 iterable 为空),返回 True;否则返回 False。
print(all([True, True, False])) # 输出 False
print(all([1, 2, 3])) # 输出 True
print(all([])) # 输出 True
3. any()
如果 iterable 中的任何元素为 True,则返回 True;否则返回 False。
print(any([False, False, True])) # 输出 True
print(any([False, False])) # 输出 False
4. bin()
将整数转换为二进制字符串(以 '0b' 开头)。
print(bin(10)) # 输出 '0b1010'
5. bool()
将值转换为布尔值。bool(None) 和 bool(0) 都返回 False,其他情况返回 True。
print(bool(0)) # 输出 False
print(bool(1)) # 输出 True
print(bool('text')) # 输出 True
6. bytearray()
返回一个新的 bytearray 对象,支持可变字节序列。
b = bytearray(b'hello')
b[0] = ord('H')
print(b) # 输出 bytearray(b'Hello')
7. bytes()
返回一个新的 bytes 对象,不可变字节序列。
b = bytes('hello', 'utf-8')
print(b) # 输出 b'hello'
8. chr()
将整数转换为其对应的字符(基于 Unicode)。
print(chr(65)) # 输出 'A'
print(chr(9731)) # 输出 '?'
9. classmethod()
将方法转换为类方法。主要用于类定义中。
class MyClass:
@classmethod
def class_method(cls):
return cls
print(MyClass.class_method()) # 输出 <class '__main__.MyClass'>
10. compile()
编译源代码为代码对象,供 exec() 或 eval() 使用。
code = compile('print("Hello")', '', 'exec')
exec(code) # 输出 Hello
11. complex()
创建一个复数对象,默认实部和虚部为 0。
c = complex(2, 3)
print(c) # 输出 (2+3j)
12. delattr()
删除对象的属性。
class MyClass:
attr = 5
obj = MyClass()
delattr(obj, 'attr')
print(hasattr(obj, 'attr')) # 输出 False
13. dict()
创建一个字典对象。
d = dict(a=1, b=2)
print(d) # 输出 {'a': 1, 'b': 2}
14. dir()
返回对象的属性和方法列表。
print(dir([])) # 输出列表对象的所有属性和方法
15. divmod()
返回两个数的商和余数的元组。
print(divmod(9, 4)) # 输出 (2, 1)
16. enumerate()
返回可迭代对象的枚举对象,通常用于循环遍历。
for index, value in enumerate(['a', 'b', 'c']):
print(index, value)
# 输出:
# 0 a
# 1 b
# 2 c
17. eval()
执行表达式并返回结果。需谨慎使用,避免安全问题。
print(eval('3 + 5')) # 输出 8
18. exec()
执行动态生成的 Python 代码。
exec('for i in range(3): print(i)')
# 输出:
# 0
# 1
# 2
19. exit()
退出解释器。
# exit() # 运行此行代码将退出 Python 解释器
20. filter()
返回一个迭代器,包含 iterable 中符合函数条件的元素。
def is_even(n):
return n % 2 == 0
print(list(filter(is_even, [1, 2, 3, 4]))) # 输出 [2, 4]
21. float()
将值转换为浮点数。
print(float('3.14')) # 输出 3.14
22. format()
格式化字符串。
print('{:.2f}'.format(3.14159)) # 输出 3.14
23. frozenset()
创建一个不可变的集合对象。
fset = frozenset([1, 2, 3])
print(fset) # 输出 frozenset({1, 2, 3})
24. getattr()
获取对象的属性值。
class MyClass:
attr = 5
obj = MyClass()
print(getattr(obj, 'attr')) # 输出 5
25. globals()
返回当前全局符号表的字典。
print(globals()) # 输出当前全局命名空间
26. hasattr()
检查对象是否有指定的属性。
class MyClass:
attr = 5
obj = MyClass()
print(hasattr(obj, 'attr')) # 输出 True
27. hash()
返回对象的哈希值,主要用于字典和集合。
print(hash('example')) # 输出字符串 'example' 的哈希值
28. help()
调用内置帮助系统,提供文档和说明。
help(print) # 显示 print 函数的帮助信息
29. hex()
将整数转换为十六进制字符串(以 '0x' 开头)。
print(hex(255)) # 输出 '0xff'
30. id()
返回对象的唯一标识符(内存地址)。
x = 5
print(id(x)) # 输出对象 x 的唯一标识符
31. input()
从用户处获取输入数据。
name = input('Enter your name: ')
print(f'Hello, {name}!')
32. int()
将值转换为整数。
print(int('42')) # 输出 42
33. isinstance()
检查对象是否是指定类的实例。
print(isinstance(5, int)) # 输出 True
print(isinstance('text', str)) # 输出 True
34. issubclass()
检查类是否是指定基类的子类。
print(issubclass(bool, int)) # 输出 True
35. iter()
返回可迭代对象的迭代器。
iterable = [1, 2, 3]
iterator = iter(iterable)
print(next(iterator)) # 输出 1
36. len()
返回对象的长度或元素个数。
print(len('hello')) # 输出 5
print(len([1, 2, 3])) # 输出 3
37. list()
将可迭代对象转换为列表。
print(list('abc')) # 输出 ['a', 'b', 'c']
38. locals()
返回当前局部符号表的字典。
def example():
x = 5
print(locals()) # 输出 {'x': 5}
example()
39. map()
将函数应用于 iterable 的每个元素,返回一个迭代器。
def square(n):
return n * n
print(list(map(square, [1, 2, 3, 4]))) # 输出 [1, 4, 9, 16]
40. max()
返回 iterable 中的最大值,或多个参数中的最大值。
print(max([1, 2
, 3, 4])) # 输出 4
print(max(1, 5, 3)) # 输出 5
41. memoryview()
创建一个内存视图对象,支持对字节对象的切片操作。
m = memoryview(b'hello')
print(m[0]) # 输出 104 (字节 'h' 的值)
42. min()
返回 iterable 中的最小值,或多个参数中的最小值。
print(min([1, 2, 3, 4])) # 输出 1
print(min(1, 5, 3)) # 输出 1
43. next()
返回迭代器的下一个元素。
iterator = iter([1, 2, 3])
print(next(iterator)) # 输出 1
44. object()
返回一个新对象,所有类的基类。
obj = object()
print(obj) # 输出 <object object at ...>
45. oct()
将整数转换为八进制字符串(以 '0o' 开头)。
print(oct(8)) # 输出 '0o10'
46. open()
打开一个文件,并返回文件对象。
with open('example.txt', 'w') as f:
f.write('Hello, world!')
47. ord()
将字符转换为其对应的 Unicode 代码点。
print(ord('A')) # 输出 65
48. pow()
返回 x 的 y 次幂(x^y),或对 (x^y) % z 的结果。
print(pow(2, 3)) # 输出 8
print(pow(2, 3, 5)) # 输出 3
49. print()
将数据输出到控制台或文件。
print('Hello, world!') # 输出 Hello, world!
50. property()
返回属性装饰器,定义类的属性。
class MyClass:
def __init__(self, value):
self._value = value
@property
def value(self):
return self._value
obj = MyClass(10)
print(obj.value) # 输出 10
51. quit()
退出解释器。
# quit() # 运行此行代码将退出 Python 解释器
52. range()
返回一个可迭代对象,生成一系列整数。
print(list(range(5))) # 输出 [0, 1, 2, 3, 4]
53. repr()
返回对象的字符串表示形式。
print(repr('hello')) # 输出 "'hello'"
54. reversed()
返回可迭代对象的反向迭代器。
print(list(reversed([1, 2, 3]))) # 输出 [3, 2, 1]
55. round()
返回浮点数四舍五入到指定小数位数。
print(round(3.14159, 2)) # 输出 3.14
56. set()
创建一个新的集合对象。
print(set([1, 2, 2, 3])) # 输出 {1, 2, 3}
57. setattr()
设置对象的属性值。
class MyClass:
pass
obj = MyClass()
setattr(obj, 'attr', 5)
print(obj.attr) # 输出 5
58. slice()
创建一个切片对象。
s = slice(1, 5, 2)
print(range(10)[s]) # 输出 range(1, 5, 2) 的切片 [1, 3]
59. sorted()
返回一个排序后的列表。
print(sorted([3, 1, 2])) # 输出 [1, 2, 3]
60. staticmethod()
将方法转换为静态方法,主要用于类定义中。
class MyClass:
@staticmethod
def static_method():
return 'Static method called'
print(MyClass.static_method()) # 输出 'Static method called'
61. str()
将对象转换为字符串。
print(str(123)) # 输出 '123'
62. sum()
返回 iterable 元素的总和。
print(sum([1, 2, 3])) # 输出 6
63. super()
返回父类的一个代理对象,用于调用父类的方法。
class Parent:
def greet(self):
return 'Hello'
class Child(Parent):
def greet(self):
return super().greet() + ' World'
print(Child().greet()) # 输出 'Hello World'
64. tuple()
将可迭代对象转换为元组。
print(tuple([1, 2, 3])) # 输出 (1, 2, 3)
65. type()
返回对象的类型,或创建新的类型对象。
print(type(123)) # 输出 <class 'int'>
print(type('text')) # 输出 <class 'str'>
66. vars()
返回对象的 dict 属性,即对象的属性字典。
class MyClass:
attr = 5
print(vars(MyClass)) # 输出 {'__module__': '__main__', 'attr': 5, ...}
67. zip()
将多个可迭代对象打包成一个迭代器,返回元组的迭代器。
print(list(zip([1, 2], ['a', 'b']))) # 输出 [(1, 'a'), (2, 'b')]
68. __import__()
动态导入模块。
math = __import__('math')
print(math.sqrt(16)) # 输出 4.0
总结
Python 3 提供了丰富的内置函数,用于处理各种编程任务。这些函数涵盖了数据类型转换、序列处理、文件操作、数学计算、动态代码执行等方面。掌握这些内置函数可以显著提高编程效率,使你的代码更加简洁和高效。