目录
7. bytearray([source[, encoding[, errors]]])
11. compile(source, filename, mode[, flags[, dont_inherit]])
16. enumerate(iterable, start=0)
17. eval(expression[, globals[, locals]])
18. exec(object[, globals[, locals]])
19. filter(function_or_none, iterable)
21. format(value[, format_spec])
23. getattr(object, name[, default])
32. isinstance(object, classinfo)
33. issubclass(class, classinfo)
38. map(function, iterable, ...)
39. max(iterable[, key, default])
41. min(iterable[, key, default])
48. print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
49. property([fget[, fset[, fdel[, doc]]]])
55. setattr(object, name, value)
56. slice(start, stop[, step])
57. sorted(iterable[, key][, reverse])
Python 3 提供了许多内置函数,这些函数可以帮助开发者快速地完成常见的编程任务,如数据类型转换、容器操作、迭代器处理等。以下是 Python 3 中一些常用的内置函数及其简要介绍。
常用的内置函数
1. abs(x)
返回数字 x 的绝对值。
python
深色版本
1print(abs(-5)) # 输出: 5
2. all(iterable)
如果可迭代对象 iterable 中的所有元素都为 True,则返回 True;如果有任何一个元素为 False,则返回 False。空的 iterable 返回 True。
python
深色版本
1print(all([True, True, True])) # 输出: True
2print(all([True, False, True])) # 输出: False
3. any(iterable)
如果可迭代对象 iterable 中至少有一个元素为 True,则返回 True;否则返回 False。空的 iterable 返回 False。
python
深色版本
1print(any([False, False, True])) # 输出: True
2print(any([False, False, False])) # 输出: False
4. ascii(obj)
返回对象的一个可打印的表示形式,通常是 ASCII 编码的字符串。
python
深色版本
1print(ascii('你好')) # 输出: '你好'
5. bin(x)
将整数 x 转换为其二进制表示形式的字符串。
python
深色版本
1print(bin(10)) # 输出: '0b1010'
6. bool(x)
将 x 转换为布尔值,如果 x 是 True 或者 False,则直接返回 True 或 False。
python
深色版本
1print(bool(1)) # 输出: True
2print(bool(0)) # 输出: False
7. bytearray([source[, encoding[, errors]]])
返回一个新的 bytearray 对象,如果提供了源数据,则使用给定的编码和错误处理策略。
python
深色版本
1print(bytearray([65, 66, 67])) # 输出: bytearray(b'ABC')
8. callable(object)
判断对象是否可调用(即是否是一个函数、方法或其他可调用的对象)。
python
深色版本
1print(callable(len)) # 输出: True
2print(callable(5)) # 输出: False
9. chr(i)
返回 Unicode 码位 i 的字符。
python
深色版本
1print(chr(65)) # 输出: 'A'
10. classmethod(function)
将一个函数转换为类方法。
python
深色版本
1class MyClass:
2 @classmethod
3 def class_method(cls):
4 return cls
5
6print(MyClass.class_method()) # 输出: <class '__main__.MyClass'>
11. compile(source, filename, mode[, flags[, dont_inherit]])
编译源码为代码或 AST 对象。
python
深色版本
1code = compile("a = 5", "<string>", "exec")
2exec(code)
3print(a) # 输出: 5
12. delattr(object, name)
删除指定对象的属性。
python
深色版本
1class MyClass:
2 value = 5
3
4my_instance = MyClass()
5delattr(my_instance, 'value')
6print(hasattr(my_instance, 'value')) # 输出: False
13. dict([arg])
创建一个新的字典。
python
深色版本
1print(dict(one=1, two=2, three=3)) # 输出: {'one': 1, 'two': 2, 'three': 3}
14. dir([object])
返回对象的属性列表。
python
深色版本
1print(dir([])) # 输出: ['append', 'clear', 'copy', ...]
15. divmod(x, y)
同时返回 x 除以 y 的商和余数。
python
深色版本
1print(divmod(10, 3)) # 输出: (3, 1)
16. enumerate(iterable, start=0)
返回一个枚举对象,它可以生成索引和值。
python
深色版本
1for index, value in enumerate(['apple', 'banana', 'cherry']):
2 print(index, value)
3# 输出:
4# 0 apple
5# 1 banana
6# 2 cherry
17. eval(expression[, globals[, locals]])
计算表达式并返回结果。
python
深色版本
1print(eval('1 + 2')) # 输出: 3
18. exec(object[, globals[, locals]])
执行动态生成的 Python 代码。
python
深色版本
1exec('print("Hello, World!")') # 输出: Hello, World!
19. filter(function_or_none, iterable)
构造一个迭代器,从 iterable 中过滤出使 function 为 True 的元素。
python
深色版本
1numbers = [1, 2, 3, 4, 5, 6]
2even_numbers = filter(lambda x: x % 2 == 0, numbers)
3print(list(even_numbers)) # 输出: [2, 4, 6]
20. float(x)
将 x 转换为浮点数。
python
深色版本
1print(float('3.14')) # 输出: 3.14
21. format(value[, format_spec])
格式化字符串。
python
深色版本
1print(format(3.14159, '.2f')) # 输出: '3.14'
22. frozenset([iterable])
返回一个新的不可变集合。
python
深色版本
1print(frozenset([1, 2, 3, 1])) # 输出: frozenset({1, 2, 3})
23. getattr(object, name[, default])
获取对象的属性值。
python
深色版本
1class MyClass:
2 value = 5
3
4my_instance = MyClass()
5print(getattr(my_instance, 'value')) # 输出: 5
24. globals()
返回当前全局符号表的字典。
python
深色版本
1print(globals().get('__name__', 'Unknown')) # 输出: '__main__'
25. hasattr(object, name)
检查对象是否有给定名称的属性。
python
深色版本
1class MyClass:
2 value = 5
3
4my_instance = MyClass()
5print(hasattr(my_instance, 'value')) # 输出: True
26. hash(object)
返回对象的哈希值。
python
深色版本
1print(hash(5)) # 输出: 5
27. help([object])
显示对象的帮助信息。
python
深色版本
1help(print) # 显示关于 print 函数的帮助信息
28. hex(x)
将整数 x 转换为其十六进制表示形式的字符串。
python
深色版本
1print(hex(10)) # 输出: '0xa'
29. id(object)
返回对象的唯一标识符。
python
深色版本
1print(id(5)) # 输出: 一个唯一的标识符
30. input([prompt])
从标准输入读取一行。
python
深色版本
1name = input("请输入你的名字: ")
2print("你好,", name)
31. int(x[, base])
将 x 转换为整数。
python
深色版本
1print(int('100', 2)) # 输出: 4
32. isinstance(object, classinfo)
检查对象是否为指定类的实例。
python
深色版本
1class MyClass:
2 pass
3
4obj = MyClass()
5print(isinstance(obj, MyClass)) # 输出: True
33. issubclass(class, classinfo)
检查类是否是另一个类的子类。
python
深色版本
1class Base:
2 pass
3
4class Derived(Base):
5 pass
6
7print(issubclass(Derived, Base)) # 输出: True
34. iter(object[, sentinel])
返回一个迭代器。
python
深色版本
1numbers = [1, 2, 3]
2it = iter(numbers)
3print(next(it)) # 输出: 1
35. len(s)
返回对象的长度(如果是序列)或元素数量(如果是集合)。
python
深色版本
1print(len([1, 2, 3])) # 输出: 3
36. list([iterable])
创建一个新的列表。
python
深色版本
1print(list('hello')) # 输出: ['h', 'e', 'l', 'l', 'o']
37. locals()
返回当前局部符号表的字典。
python
深色版本
1print(locals()) # 输出: 包含当前作用域内所有变量的字典
38. map(function, iterable, ...)
应用函数 function 到 iterable 的每个元素上,并返回一个迭代器。
python
深色版本
1numbers = [1, 2, 3]
2squares = map(lambda x: x**2, numbers)
3print(list(squares)) # 输出: [1, 4, 9]
39. max(iterable[, key, default])
返回可迭代对象中的最大值。
python
深色版本
1print(max([1, 2, 3])) # 输出: 3
40. memoryview(obj)
返回一个内存视图对象。
python
深色版本
1buf = b'ABCD'
2mv = memoryview(buf)
3print(mv) # 输出: <memory at 0x7f9e4b4f7700>
41. min(iterable[, key, default])
返回可迭代对象中的最小值。
python
深色版本
1print(min([1, 2, 3])) # 输出: 1
42. next(iterator[, default])
返回迭代器的下一个项目。
python
深色版本
1it = iter([1, 2, 3])
2print(next(it)) # 输出: 1
43. object()
返回一个空对象。
python
深色版本
1print(object()) # 输出: <object object at 0x7f9e4b4f7700>
44. oct(x)
将整数 x 转换为其八进制表示形式的字符串。
python
深色版本
1print(oct(10)) # 输出: '0o12'
45. open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
打开一个文件,并返回一个文件对象。
python
深色版本
1with open('test.txt', 'w') as f:
2 f.write('Hello, World!')
46. ord(c)
返回单个字符 c 的 Unicode 码位值。
python
深色版本
1print(ord('A')) # 输出: 65
47. pow(base, exp[, mod])
返回 base 的 exp 次幂,如果提供了 mod,则返回模 mod 的结果。
python
深色版本
1print(pow(2, 3)) # 输出: 8
48. print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
打印对象到标准输出流。
python
深色版本
1print("Hello,", "World!", sep=" ", end="!\n")
49. property([fget[, fset[, fdel[, doc]]]])
将一个方法转换为属性。
python
深色版本
1class MyClass:
2 def __init__(self, value):
3 self._value = value
4
5 @property
6 def value(self):
7 return self._value
8
9obj = MyClass(5)
10print(obj.value) # 输出: 5
50. range(stop)
返回一个范围对象。
python
深色版本
1print(list(range(5))) # 输出: [0, 1, 2, 3, 4]
51. repr(object)
返回对象的字符串表示形式。
python
深色版本
1print(repr(5)) # 输出: '5'
52. reversed(seq)
返回一个反向迭代器。
python
深色版本
1for i in reversed([1, 2, 3]):
2 print(i)
3# 输出:
4# 3
5# 2
6# 1
53. round(number[, ndigits])
四舍五入一个数字。
python
深色版本
1print(round(3.14159, 2)) # 输出: 3.14
54. set([iterable])
创建一个新的集合。
python
深色版本
1print(set([1, 2, 3, 1])) # 输出: {1, 2, 3}
55. setattr(object, name, value)
设置对象的属性值。
python
深色版本
1class MyClass:
2 pass
3
4obj = MyClass()
5setattr(obj, 'value', 5)
6print(obj.value) # 输出: 5
56. slice(start, stop[, step])
返回一个切片对象。
python
深色版本
1s = slice(1, 5, 2)
2print(s) # 输出: slice(1, 5, 2)
57. sorted(iterable[, key][, reverse])
返回排序后的列表。
python
深色版本
1print(sorted([3, 1, 2])) # 输出: [1, 2, 3]
58. staticmethod(function)
将一个函数转换为静态方法。
python
深色版本
1class MyClass:
2 @staticmethod
3 def static_method():
4 return "Static method called."
5
6print(MyClass.static_method()) # 输出: Static method called.
59. str(object='')
将对象转换为字符串。
python
深色版本
1print(str(5)) # 输出: '5'
60. sum(iterable[, start])
计算 iterable 中所有元素的总和。
python
深色版本
1print(sum([1, 2, 3])) # 输出: 6
61. super(type, obj)
临时上调父类的方法。
python
深色版本
1class Base:
2 def method(self):
3 print("Base method called.")
4
5class Derived(Base):
6 def method(self):
7 super(Derived, self).method()
8 print("Derived method called.")
9
10Derived().method()
11# 输出:
12# Base method called.
13# Derived method called.
62. tuple([iterable])
创建一个新的元组。
python
深色版本
1print(tuple('hello')) # 输出: ('h', 'e', 'l', 'l', 'o')
63. type(object)
返回对象的类型。
python
深色版本
1print(type(5)) # 输出: <class 'int'>
64. vars([object])
返回对象的 __dict__ 属性。
python
深色版本
1class MyClass:
2 value = 5
3
4obj = MyClass()
5print(vars(obj)) # 输出: {'value': 5}
65. zip(*iterables)
返回一个迭代器,它聚合多个迭代器的元素。
python
深色版本
1for a, b in zip([1, 2, 3], ['a', 'b', 'c']):
2 print(a, b)
3# 输出:
4# 1 a
5# 2 b
6# 3 c
总结
以上列出了一些常用的 Python 内置函数,它们可以帮助你在开发过程中更加高效地编写代码。每种函数都有其特定的功能和用法,熟悉它们可以帮助你更好地利用 Python 的特性。

--Python3 内置函数&spm=1001.2101.3001.5002&articleId=142265206&d=1&t=3&u=337b75cbe9fe47c8a45c1141bb73e147)
1524

被折叠的 条评论
为什么被折叠?



