前言

Python 提供了许多内置函数,这些函数可以帮助开发者更高效地编写代码。

1. abs()

返回一个数的绝对值。

1
print(abs(-5))  # 输出: 5

2. aiter()

返回一个异步迭代器。

1
2
3
4
5
6
async def async_gen():
yield 1
yield 2

async for value in aiter(async_gen()):
print(value) # 输出: 1 2

3. all()

如果可迭代对象中的所有元素都为真,返回 True;否则返回 False。

1
print(all([True, True, False]))  # 输出: False

4. any()

如果可迭代对象中至少有一个元素为真,返回 True;否则返回 False。

1
print(any([False, False, True]))  # 输出: True

5. ascii()

返回对象的可打印 ASCII 表示。

1
print(ascii('Hello, 世界'))  # 输出: 'Hello, \u4e16\u754c'

6. bin()

将整数转换为二进制字符串。

1
print(bin(5))  # 输出: '0b101'

7. bool()

将一个值转换为布尔值。

1
print(bool(0))  # 输出: False

8. breakpoint()

在调试时设置一个断点。

1
2
3
4
5
6
def debug_example():
x = 10
breakpoint() # 在此处会中断执行
print(x)

debug_example()

9. bytearray()

返回一个新的字节数组。

1
2
b = bytearray([50, 100, 76])
print(b) # 输出: bytearray(b'2dL')

10. bytes()

返回一个新的字节对象。

1
2
b = bytes([50, 100, 76])
print(b) # 输出: b'2dL'

11. callable()

检查对象是否可调用。

1
print(callable(print))  # 输出: True

12. chr()

将整数转换为对应的字符。

1
print(chr(97))  # 输出: 'a'

13. classmethod()

将方法转换为类方法。

1
2
3
4
5
6
class MyClass:
@classmethod
def my_class_method(cls):
return cls

print(MyClass.my_class_method()) # 输出: <class '__main__.MyClass'>

14. compile()

将源代码编译为代码对象。

1
2
code = compile('print("Hello World")', '<string>', 'exec')
exec(code) # 输出: Hello World

15. complex()

创建一个复数。

1
2
c = complex(1, 2)
print(c) # 输出: (1+2j)

16. delattr()

删除对象的属性。

1
2
3
4
5
6
class MyClass:
x = 10

obj = MyClass()
delattr(obj, 'x')
print(hasattr(obj, 'x')) # 输出: False

17. dict()

创建一个字典。

1
2
d = dict(a=1, b=2)
print(d) # 输出: {'a': 1, 'b': 2}

18. dir()

返回对象的属性和方法列表。

1
print(dir([]))  # 输出: 列表的所有属性和方法

19. divmod()

返回两个数的商和余数。

1
print(divmod(10, 3))  # 输出: (3, 1)

20. enumerate()

返回一个枚举对象,包含索引和相应的值。

1
2
for index, value in enumerate(['a', 'b', 'c']):
print(index, value) # 输出: 0 a 1 b 2 c

21. eval()

执行一个字符串表达式,并返回结果。

1
2
result = eval('1 + 2')
print(result) # 输出: 3

22. exec()

执行一个字符串中的 Python 代码。

1
2
exec('x = 5')
print(x) # 输出: 5

23. filter()

过滤可迭代对象中的元素。

1
2
3
4
def is_even(n):
return n % 2 == 0

print(list(filter(is_even, [1, 2, 3, 4]))) # 输出: [2, 4]

24. float()

将一个数转换为浮点数。

1
print(float(5))  # 输出: 5.0

25. format()

格式化字符串。

1
print(format(123.456, '.2f'))  # 输出: '123.46'

26. frozenset()

返回一个不可变的集合。

1
2
fs = frozenset([1, 2, 3])
print(fs) # 输出: frozenset({1, 2, 3})

27. getattr()

返回对象的属性值。

1
2
3
4
5
class MyClass:
x = 10

obj = MyClass()
print(getattr(obj, 'x')) # 输出: 10

28. globals()

返回当前全局符号表的字典。

1
2
a = 10
print(globals()['a']) # 输出: 10

29. hasattr()

检查对象是否具有指定的属性。

1
2
3
4
5
class MyClass:
x = 10

obj = MyClass()
print(hasattr(obj, 'x')) # 输出: True

30. hash()

返回对象的哈希值。

1
print(hash('hello'))  # 输出: 哈希值

31. help()

调用帮助系统。

1
help(str)  # 输出: str 类的帮助信息

32. hex()

将整数转换为十六进制字符串。

1
print(hex(255))  # 输出: '0xff'

33. id()

返回对象的唯一标识符。

1
2
x = 10
print(id(x)) # 输出: 对象的唯一标识符

34. input()

从用户输入中读取一行。

1
2
name = input("Enter your name: ")
print(f"Hello, {name}!")

35. int()

将一个数转换为整数。

1
print(int(3.14))  # 输出: 3

36. isinstance()

检查对象是否是指定类的实例。

1
print(isinstance(5, int))  # 输出: True

37. issubclass()

检查一个类是否是另一个类的子类。

1
2
3
4
class A: pass
class B(A): pass

print(issubclass(B, A)) # 输出: True

38. iter()

返回可迭代对象的迭代器。

1
2
3
my_list = [1, 2, 3]
it = iter(my_list)
print(next(it)) # 输出: 1

39. len()

返回对象的长度。

1
print(len([1, 2, 3]))  # 输出: 3

40. list()

创建一个列表。

1
print(list((1, 2, 3)))  # 输出: [1, 2, 3]

41. locals()

返回当前局部符号表的字典。

1
2
3
4
5
def my_func():
a = 10
print(locals()) # 输出: {'a': 10}

my_func()

42. map()

将函数应用于可迭代对象的每个元素。

1
2
3
4
def square(n):
return n * n

print(list(map(square, [1, 2, 3]))) # 输出: [1, 4, 9]

43. max()

返回可迭代对象中的最大值。

1
print(max([1, 2, 3]))  # 输出: 3

44. memoryview()

返回一个内存视图对象。

1
2
3
b = bytearray(b'hello')
mv = memoryview(b)
print(mv[0]) # 输出: 104 (ASCII值)

45. min()

返回可迭代对象中的最小值。

1
print(min([1, 2, 3]))  # 输出: 1

46. next()

返回迭代器的下一个值。

1
2
my_iter = iter([1, 2, 3])
print(next(my_iter)) # 输出: 1

47. object()

返回一个新的对象(通常是基类)。

1
2
obj = object()
print(obj) # 输出: <object object at 0x...>

48. oct()

将整数转换为八进制字符串。

1
print(oct(8))  # 输出: '0o10'

49. open()

打开一个文件并返回文件对象。

1
2
with open('test.txt', 'w') as f:
f.write('Hello, World!')

50. ord()

将字符转换为对应的整数(ASCII值)。

1
print(ord('a'))  # 输出: 97

51. pow()

返回 xx 的 yy 次方。

1
print(pow(2, 3))  # 输出: 8

52. print()

输出到控制台。

1
print("Hello, World!")  # 输出: Hello, World!

53. property()

返回属性的描述符。

1
2
3
4
5
6
7
8
9
10
class MyClass:
def __init__(self):
self._x = 0

@property
def x(self):
return self._x

obj = MyClass()
print(obj.x) # 输出: 0

54. range()

返回一个可迭代的整数序列。

1
print(list(range(5)))  # 输出: [0, 1, 2, 3, 4]

55. repr()

返回对象的字符串表示。

1
print(repr('Hello'))  # 输出: "'Hello'"

56. reversed()

返回一个反向迭代器。

1
print(list(reversed([1, 2, 3])))  # 输出: [3, 2, 1]

57. round()

返回浮点数的四舍五入值。

1
print(round(3.14159, 2))  # 输出: 3.14

58. set()

创建一个集合。

1
2
s = set([1, 2, 2, 3])
print(s) # 输出: {1, 2, 3}

59. setattr()

设置对象的属性值。

1
2
3
4
5
6
class MyClass:
pass

obj = MyClass()
setattr(obj, 'x', 10)
print(obj.x) # 输出: 10

60. slice()

返回一个切片对象。

1
2
s = slice(1, 5)
print(list(range(10))[s]) # 输出: [1, 2, 3, 4]

61. sorted()

返回一个排序后的列表。

1
print(sorted([3, 1, 2]))  # 输出: [1, 2, 3]

62. staticmethod()

将方法转换为静态方法。

1
2
3
4
5
6
class MyClass:
@staticmethod
def my_static_method():
return 'Hello'

print(MyClass.my_static_method()) # 输出: Hello

63. str()

将对象转换为字符串。

1
print(str(123))  # 输出: '123'

64. sum()

返回可迭代对象中所有元素的和。

1
print(sum([1, 2, 3]))  # 输出: 6

65. super()

返回父类的一个代理对象。

1
2
3
4
5
6
7
8
9
10
class A:
def greet(self):
return "Hello from A!"

class B(A):
def greet(self):
return super().greet() + " and B!"

obj = B()
print(obj.greet()) # 输出: Hello from A! and B!

66. tuple()

创建一个元组。

1
2
t = tuple([1, 2, 3])
print(t) # 输出: (1, 2, 3)

67. type()

返回对象的类型。

1
print(type(5))  # 输出: <class 'int'>

68. vars()

返回对象的 __dict__ 属性。

1
2
3
4
5
class MyClass:
x = 10

obj = MyClass()
print(vars(obj)) # 输出: {'x': 10}

69. zip()

将可迭代对象打包成元组。

1
print(list(zip([1, 2, 3], ['a', 'b', 'c'])))  # 输出: [(1, 'a'), (2, 'b'), (3, 'c')]

70. __import__()

用于动态导入模块。

1
2
math = __import__('math')
print(math.sqrt(16)) # 输出: 4.0