Python 内置函数全面详解
Python 作为一门强大而灵活的编程语言,提供了丰富的内置函数,这些函数无需导入任何模块即可直接使用。它们涵盖了各种常见编程任务,从数学运算到数据转换,再到迭代器操作。本文将详细讲解每一个内置函数,并提供独立的代码示例。
什么是内置函数?
内置函数是 Python 解释器内置的函数,在任何 Python 环境中都可以直接使用。你可以通过 dir(__builtins__)
查看所有内置函数和异常。
# 查看所有内置函数和异常
print(dir(__builtins__))
让我们开始逐一讲解每个内置函数:
1. abs(x)
返回一个数的绝对值。参数可以是整数、浮点数或实现了 __abs__()
方法的对象。
# abs() 示例
print(abs(-5)) # 输出: 5
print(abs(3.14)) # 输出: 3.14
print(abs(-2.5)) # 输出: 2.5
print(abs(0)) # 输出: 0
2. all(iterable)
如果可迭代对象中的所有元素都为真(或可迭代对象为空),返回 True
,否则返回 False
。
# all() 示例
print(all([True, 1, "hello"])) # 输出: True
print(all([True, 0, "hello"])) # 输出: False
print(all([])) # 输出: True (空列表)
print(all([1, 2, 3])) # 输出: True
print(all([1, 0, 3])) # 输出: False
3. any(iterable)
如果可迭代对象中任何元素为真,返回 True
。如果可迭代对象为空,返回 False
。
# any() 示例
print(any([False, 0, ""])) # 输出: False
print(any([False, 1, ""])) # 输出: True
print(any([])) # 输出: False
print(any([0, 0.0, 0j])) # 输出: False
4. ascii(object)
返回一个表示对象的字符串,但会将非 ASCII 字符转义。
# ascii() 示例
print(ascii("hello")) # 输出: 'hello'
print(ascii("café")) # 输出: 'caf\xe9'
print(ascii("北京")) # 输出: '\u5317\u4eac'
print(ascii([1, 2, "hello"])) # 输出: [1, 2, 'hello']
5. bin(x)
将一个整数转换为以 “0b” 开头的二进制字符串。
# bin() 示例
print(bin(10)) # 输出: 0b1010
print(bin(0)) # 输出: 0b0
print(bin(-5)) # 输出: -0b101
6. bool(x)
返回一个布尔值,即 True
或 False
。使用标准真值测试过程进行转换。
# bool() 示例
print(bool(0)) # 输出: False
print(bool(1)) # 输出: True
print(bool("")) # 输出: False
print(bool("hello")) # 输出: True
print(bool([])) # 输出: False
print(bool([1, 2])) # 输出: True
7. breakpoint()
进入调试器(Python 3.7+)。这是一个调试工具,用于设置断点。
# breakpoint() 示例
def test_function():
x = 10
y = 20
# breakpoint() # 取消注释这行来测试
return x + y
# test_function()
8. bytearray(source, encoding, errors)
返回一个新的字节数组。字节数组是可变的字节序列。
# bytearray() 示例
# 从整数创建
ba1 = bytearray([65, 66, 67])
print(ba1) # 输出: bytearray(b'ABC')
# 从字符串创建(需要指定编码)
ba2 = bytearray("hello", "utf-8")
print(ba2) # 输出: bytearray(b'hello')
# 修改字节数组
ba2[0] = 72 # 'H' 的 ASCII 码
print(ba2) # 输出: bytearray(b'Hello')
9. bytes(source, encoding, errors)
返回一个新的不可变字节对象。
# bytes() 示例
# 从整数创建
b1 = bytes([65, 66, 67])
print(b1) # 输出: b'ABC'
# 从字符串创建
b2 = bytes("hello", "utf-8")
print(b2) # 输出: b'hello'
# 字节对象是不可变的
# b2[0] = 72 # 这会抛出 TypeError
10. callable(object)
如果对象是可调用的(如函数、方法、类等),返回 True
,否则返回 False
。
# callable() 示例
def my_function():
pass
class MyClass:
def method(self):
pass
print(callable(my_function)) # 输出: True
print(callable(MyClass)) # 输出: True
print(callable("hello")) # 输出: False
print(callable([1, 2, 3])) # 输出: False
11. chr(i)
返回 Unicode 码位为整数 i 的字符的字符串格式。
# chr() 示例
print(chr(65)) # 输出: 'A'
print(chr(97)) # 输出: 'a'
print(chr(20320)) # 输出: '你' (中文"你"的Unicode)
print(chr(128512)) # 输出: '😀' (笑脸表情)
12. classmethod(function)
将函数转换为类方法。类方法将类作为第一个参数接收。
# classmethod() 示例
class MyClass:
count = 0
def __init__(self):
MyClass.count += 1
@classmethod
def get_count(cls):
return cls.count
obj1 = MyClass()
obj2 = MyClass()
print(MyClass.get_count()) # 输出: 2
13. compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
将源代码编译为代码或 AST 对象。
# compile() 示例
code_str = "x = 5\ny = 10\nresult = x + y\nprint(result)"
compiled_code = compile(code_str, "<string>", "exec")
exec(compiled_code) # 输出: 15
14. complex(real, imag)
返回一个值为 real + imag * 1j 的复数,或将字符串或数字转换为复数。
# complex() 示例
print(complex(3, 4)) # 输出: (3+4j)
print(complex(7)) # 输出: (7+0j)
print(complex("3+4j")) # 输出: (3+4j)
print(complex("-5.2j")) # 输出: (-0-5.2j)
15. delattr(object, name)
删除对象的命名属性。相当于 del obj.name
。
# delattr() 示例
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 30)
print(hasattr(p, "name")) # 输出: True
delattr(p, "name")
print(hasattr(p, "name")) # 输出: False
16. dict(**kwarg)
17. dict(mapping, **kwarg)
18. dict(iterable, **kwarg)
创建一个新的字典。
# dict() 示例
# 创建空字典
d1 = dict()
print(d1) # 输出: {}
# 使用关键字参数
d2 = dict(a=1, b=2, c=3)
print(d2) # 输出: {'a': 1, 'b': 2, 'c': 3}
# 从可迭代对象创建
d3 = dict([('a', 1), ('b', 2), ('c', 3)])
print(d3) # 输出: {'a': 1, 'b': 2, 'c': 3}
# 从映射创建
d4 = dict({'a': 1, 'b': 2}, c=3, d=4)
print(d4) # 输出: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
19. dir(object)
如果没有参数,返回当前本地作用域中的名称列表。如果有参数,尝试返回该对象的有效属性列表。
# dir() 示例
# 无参数
print(dir()[:5]) # 输出当前作用域的前5个名称
# 有参数
print(dir(str)[:10]) # 输出str对象的前10个属性
20. divmod(a, b)
返回一个包含商和余数的元组 (a // b, a % b)
。
# divmod() 示例
print(divmod(10, 3)) # 输出: (3, 1)
print(divmod(10.5, 2)) # 输出: (5.0, 0.5)
print(divmod(-10, 3)) # 输出: (-4, 2)
21. enumerate(iterable, start=0)
返回一个枚举对象。iterable 必须是一个序列、迭代器或其他支持迭代的对象。
# enumerate() 示例
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
# 输出:
# Index 0: apple
# Index 1: banana
# Index 2: cherry
# 指定起始值
for index, fruit in enumerate(fruits, start=1):
print(f"#{index}: {fruit}")
# 输出:
# #1: apple
# #2: banana
# #3: cherry
22. eval(expression, globals=None, locals=None)
执行一个字符串表达式,并返回表达式的值。
# eval() 示例
x = 10
y = 20
result = eval("x + y")
print(result) # 输出: 30
# 使用全局和局部命名空间
namespace = {'a': 2, 'b': 3}
result = eval("a * b", namespace)
print(result) # 输出: 6
23. exec(object, globals=None, locals=None)
动态执行 Python 代码。object 必须是字符串或代码对象。
# exec() 示例
code = """
def greet(name):
return f"Hello, {name}!"
message = greet("World")
print(message)
"""
exec(code) # 输出: Hello, World!
24. filter(function, iterable)
用 iterable 中函数 function 返回真的那些元素,构建一个新的迭代器。
# filter() 示例
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 过滤偶数
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # 输出: [2, 4, 6, 8, 10]
# 过滤大于5的数
greater_than_5 = list(filter(lambda x: x > 5, numbers))
print(greater_than_5) # 输出: [6, 7, 8, 9, 10]
25. float(x)
从数字或字符串 x 生成一个浮点数。
# float() 示例
print(float(10)) # 输出: 10.0
print(float("3.14")) # 输出: 3.14
print(float("-5.2")) # 输出: -5.2
print(float()) # 输出: 0.0
26. format(value, format_spec)
将 value 转换为 format_spec 控制的"格式化"表示。
# format() 示例
# 数字格式化
print(format(123.45678, ".2f")) # 输出: 123.46
print(format(1000000, ",")) # 输出: 1,000,000
print(format(0.25, ".0%")) # 输出: 25%
# 字符串格式化
print(format("hello", "^10")) # 输出: ' hello '
print(format("hello", ">10")) # 输出: ' hello'
print(format("hello", "<10")) # 输出: 'hello '
# 二进制、八进制、十六进制
print(format(255, "b")) # 输出: '11111111'
print(format(255, "o")) # 输出: '377'
print(format(255, "x")) # 输出: 'ff'
27. frozenset(iterable)
返回一个新的 frozenset 对象,它是一个不可变的集合。
# frozenset() 示例
numbers = [1, 2, 3, 2, 1]
fs = frozenset(numbers)
print(fs) # 输出: frozenset({1, 2, 3})
# frozenset 是不可变的
# fs.add(4) # 这会抛出 AttributeError
# 可以作为字典的键
d = {fs: "frozen set"}
print(d) # 输出: {frozenset({1, 2, 3}): 'frozen set'}
28. getattr(object, name, default)
返回对象命名属性的值。name 必须是字符串。
# getattr() 示例
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 30)
# 获取属性
name = getattr(p, "name")
print(name) # 输出: Alice
# 使用默认值
email = getattr(p, "email", "未设置")
print(email) # 输出: 未设置
29. globals()
返回实现当前模块命名空间的字典。
# globals() 示例
x = 10
y = "hello"
def test():
z = 20
print("局部变量:", locals())
print("全局变量:", globals().keys())
test()
30. hasattr(object, name)
如果对象有指定的属性,返回 True
,否则返回 False
。
# hasattr() 示例
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Bob", 25)
print(hasattr(p, "name")) # 输出: True
print(hasattr(p, "email")) # 输出: False
31. hash(object)
返回对象的哈希值(如果它有的话)。哈希值是整数。
# hash() 示例
print(hash("hello")) # 输出: 一个整数
print(hash(123)) # 输出: 123
print(hash((1, 2, 3))) # 输出: 一个整数
# 不可哈希的对象会抛出 TypeError
# print(hash([1, 2, 3])) # 这会抛出 TypeError
32. help(object)
调用内置的帮助系统。
# help() 示例
# 取消注释下面的行来测试
# help(str) # 显示str类的帮助
# help(print) # 显示print函数的帮助
33. hex(x)
将整数转换为以 “0x” 为前缀的小写十六进制字符串。
# hex() 示例
print(hex(255)) # 输出: 0xff
print(hex(16)) # 输出: 0x10
print(hex(-42)) # 输出: -0x2a
34. id(object)
返回对象的"标识值"。该值是一个整数,在此对象的生命周期中保证是唯一且恒定的。
# id() 示例
x = "hello"
y = "world"
print(id(x)) # 输出: 一个整数(内存地址)
print(id(y)) # 输出: 另一个整数
35. input(prompt)
如果存在 prompt 实参,则将其写入标准输出,末尾不带换行符。
# input() 示例
# 取消注释下面的行来测试
# name = input("请输入你的名字: ")
# print(f"你好, {name}!")
36. int(x, base=10)
返回一个基于数字或字符串 x 构造的整数对象。
# int() 示例
print(int("10")) # 输出: 10
print(int("1010", 2)) # 输出: 10 (二进制)
print(int("A", 16)) # 输出: 10 (十六进制)
print(int(3.14)) # 输出: 3
print(int()) # 输出: 0
37. isinstance(object, classinfo)
如果 object 参数是 classinfo 参数的实例,或者是其(直接、间接或虚拟)子类的实例,则返回 True
。
# isinstance() 示例
class Animal:
pass
class Dog(Animal):
pass
class Cat(Animal):
pass
dog = Dog()
cat = Cat()
print(isinstance(dog, Dog)) # 输出: True
print(isinstance(dog, Animal)) # 输出: True
print(isinstance(cat, Dog)) # 输出: False
print(isinstance(123, int)) # 输出: True
38. issubclass(class, classinfo)
如果 class 是 classinfo 的子类(直接、间接或虚拟),则返回 True
。
# issubclass() 示例
class Animal:
pass
class Mammal(Animal):
pass
class Dog(Mammal):
pass
print(issubclass(Dog, Mammal)) # 输出: True
print(issubclass(Dog, Animal)) # 输出: True
print(issubclass(Mammal, Dog)) # 输出: False
39. iter(object, sentinel)
返回一个迭代器对象。
# iter() 示例
# 从可迭代对象创建迭代器
numbers = [1, 2, 3, 4, 5]
numbers_iter = iter(numbers)
print(next(numbers_iter)) # 输出: 1
print(next(numbers_iter)) # 输出: 2
# 使用哨兵值
class Counter:
def __init__(self, start=0):
self.count = start
def __iter__(self):
return self
def __next__(self):
self.count += 1
return self.count
counter = Counter()
counter_iter = iter(counter.__next__, 5) # 当返回5时停止
for num in counter_iter:
print(num) # 输出: 1, 2, 3, 4
40. len(s)
返回对象的长度(元素个数)。
# len() 示例
print(len("hello")) # 输出: 5
print(len([1, 2, 3])) # 输出: 3
print(len({"a": 1, "b": 2})) # 输出: 2
print(len((1, 2, 3, 4))) # 输出: 4
41. list(iterable)
将可迭代对象转换为列表。
# list() 示例
print(list("hello")) # 输出: ['h', 'e', 'l', 'l', 'o']
print(list((1, 2, 3))) # 输出: [1, 2, 3]
print(list({1, 2, 3})) # 输出: [1, 2, 3]
print(list({"a": 1, "b": 2})) # 输出: ['a', 'b']
print(list(range(5))) # 输出: [0, 1, 2, 3, 4]
42. locals()
更新并返回表示当前本地符号表的字典。
# locals() 示例
def test_function():
x = 10
y = "hello"
z = [1, 2, 3]
print("局部变量:", locals())
test_function()
43. map(function, iterable, …)
返回一个将 function 应用于 iterable 中每一项并输出其结果的迭代器。
# map() 示例
numbers = [1, 2, 3, 4, 5]
# 平方每个数字
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # 输出: [1, 4, 9, 16, 25]
# 转换为字符串
strings = list(map(str, numbers))
print(strings) # 输出: ['1', '2', '3', '4', '5']
# 多个可迭代对象
a = [1, 2, 3]
b = [4, 5, 6]
sums = list(map(lambda x, y: x + y, a, b))
print(sums) # 输出: [5, 7, 9]
44. max(iterable, *[, key, default])
45. max(arg1, arg2, *args[, key])
返回可迭代对象中最大的元素,或者两个及以上实参中最大的。
# max() 示例
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(max(numbers)) # 输出: 9
words = ["apple", "banana", "cherry", "date"]
print(max(words)) # 输出: 'date' (按字母顺序)
print(max(words, key=len)) # 输出: 'banana' (最长的)
# 多个参数
print(max(10, 20, 5)) # 输出: 20
46. memoryview(object)
返回由给定实参创建的"内存视图"对象。
# memoryview() 示例
# 创建字节数组
ba = bytearray(b'ABCDEF')
mv = memoryview(ba)
# 通过内存视图访问数据
print(mv[0]) # 输出: 65 (ASCII 'A')
print(mv[1:3].tobytes()) # 输出: b'BC'
# 通过内存视图修改数据
mv[2] = 88 # ASCII 'X'
print(ba) # 输出: bytearray(b'ABXDEF')
47. min(iterable, *[, key, default])
48. min(arg1, arg2, *args[, key])
返回可迭代对象中最小的元素,或者两个及以上实参中最小的。
# min() 示例
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(min(numbers)) # 输出: 1
words = ["apple", "banana", "cherry", "date"]
print(min(words)) # 输出: 'apple' (按字母顺序)
print(min(words, key=len)) # 输出: 'date' (最短的)
# 多个参数
print(min(10, 20, 5)) # 输出: 5
49. next(iterator, default)
通过调用 iterator 的 __next__()
方法获取下一个元素。
# next() 示例
numbers = iter([1, 2, 3, 4, 5])
print(next(numbers)) # 输出: 1
print(next(numbers)) # 输出: 2
print(next(numbers)) # 输出: 3
print(next(numbers, "结束")) # 输出: 4
print(next(numbers, "结束")) # 输出: 5
print(next(numbers, "结束")) # 输出: 结束
50. object()
返回一个新的无特征对象。object 是所有类的基类。
# object() 示例
obj = object()
print(type(obj)) # 输出: <class 'object'>
print(dir(obj)) # 输出对象的方法和属性
51. oct(x)
将一个整数转换为以 “0o” 为前缀的八进制字符串。
# oct() 示例
print(oct(8)) # 输出: 0o10
print(oct(64)) # 输出: 0o100
print(oct(-10)) # 输出: -0o12
52. open(file, mode=‘r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
打开文件并返回对应的文件对象。
# open() 示例
# 写入文件
with open("test.txt", "w") as f:
f.write("Hello, World!\nThis is a test file.")
# 读取文件
with open("test.txt", "r") as f:
content = f.read()
print(content)
# 逐行读取
with open("test.txt", "r") as f:
for line in f:
print(line.strip())
53. ord©
对表示单个 Unicode 字符的字符串,返回代表它 Unicode 码点的整数。
# ord() 示例
print(ord('A')) # 输出: 65
print(ord('a')) # 输出: 97
print(ord('你')) # 输出: 20320
print(ord('😊')) # 输出: 128522
54. pow(base, exp, mod=None)
返回 base 的 exp 次幂;如果 mod 存在,则返回 base 的 exp 次幂对 mod 取余。
# pow() 示例
print(pow(2, 3)) # 输出: 8 (2^3)
print(pow(2, 3, 3)) # 输出: 2 (8 % 3)
print(pow(5, 2)) # 输出: 25
print(pow(5, -2)) # 输出: 0.04
55. print(*objects, sep=’ ‘, end=’\n’, file=None, flush=False)
将 objects 打印到 file 指定的文本流,以 sep 分隔并在末尾加上 end。
# print() 示例
print("Hello", "World") # 输出: Hello World
print("Hello", "World", sep=", ") # 输出: Hello, World
print("Hello", end=" ")
print("World") # 输出: Hello World
# 打印到文件
with open("output.txt", "w") as f:
print("This goes to a file", file=f)
56. property(fget=None, fset=None, fdel=None, doc=None)
返回 property 属性。
# property() 示例
class Circle:
def __init__(self, radius):
self._radius = radius
def get_radius(self):
print("获取半径")
return self._radius
def set_radius(self, value):
print("设置半径")
if value < 0:
raise ValueError("半径不能为负")
self._radius = value
def del_radius(self):
print("删除半径")
del self._radius
radius = property(get_radius, set_radius, del_radius, "圆的半径")
circle = Circle(5)
print(circle.radius) # 输出: 获取半径 \n 5
circle.radius = 10 # 输出: 设置半径
57. range(stop)
58. range(start, stop[, step])
虽然是一个类,但通常被当作函数使用,生成一个不可变的序列。
# range() 示例
print(list(range(5))) # 输出: [0, 1, 2, 3, 4]
print(list(range(1, 5))) # 输出: [1, 2, 3, 4]
print(list(range(0, 10, 2))) # 输出: [0, 2, 4, 6, 8]
print(list(range(10, 0, -1))) # 输出: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
59. repr(object)
返回包含一个对象的可打印表示形式的字符串。
# repr() 示例
print(repr("hello")) # 输出: 'hello'
print(repr(123)) # 输出: 123
print(repr([1, 2, 3])) # 输出: [1, 2, 3]
print(repr({"a": 1, "b": 2})) # 输出: {'a': 1, 'b': 2}
60. reversed(seq)
返回一个反向的迭代器。
# reversed() 示例
numbers = [1, 2, 3, 4, 5]
rev_numbers = list(reversed(numbers))
print(rev_numbers) # 输出: [5, 4, 3, 2, 1]
string = "hello"
rev_string = ''.join(reversed(string))
print(rev_string) # 输出: olleh
61. round(number, ndigits=None)
返回 number 四舍五入到小数点后 ndigits 位精度的值。
# round() 示例
print(round(3.14159)) # 输出: 3
print(round(3.14159, 2)) # 输出: 3.14
print(round(3.14159, 4)) # 输出: 3.1416
print(round(2.675, 2)) # 输出: 2.67 (注意浮点数精度问题)
62. set(iterable)
返回一个新的 set 对象,其元素来自于 iterable。
# set() 示例
print(set([1, 2, 3, 2, 1])) # 输出: {1, 2, 3}
print(set("hello")) # 输出: {'h', 'e', 'l', 'o'}
print(set((1, 2, 3, 4))) # 输出: {1, 2, 3, 4}
print(set({"a": 1, "b": 2})) # 输出: {'a', 'b'}
63. setattr(object, name, value)
设置对象的属性值。相当于 obj.name = value
。
# setattr() 示例
class Person:
pass
p = Person()
setattr(p, "name", "Alice")
setattr(p, "age", 30)
print(p.name) # 输出: Alice
print(p.age) # 输出: 30
64. slice(stop)
65. slice(start, stop[, step])
返回一个切片对象,表示由 range(start, stop, step) 指定的索引集合。
# slice() 示例
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 创建切片对象
s1 = slice(5) # 相当于 [0:5]
s2 = slice(2, 8) # 相当于 [2:8]
s3 = slice(1, 9, 2) # 相当于 [1:9:2]
print(numbers[s1]) # 输出: [0, 1, 2, 3, 4]
print(numbers[s2]) # 输出: [2, 3, 4, 5, 6, 7]
print(numbers[s3]) # 输出: [1, 3, 5, 7]
66. sorted(iterable, key=None, reverse=False)
从 iterable 中的项返回一个新的排序列表。
# sorted() 示例
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(sorted(numbers)) # 输出: [1, 1, 2, 3, 4, 5, 6, 9]
words = ["banana", "apple", "cherry", "date"]
print(sorted(words)) # 输出: ['apple', 'banana', 'cherry', 'date']
print(sorted(words, key=len)) # 输出: ['date', 'apple', 'banana', 'cherry']
# 降序排序
print(sorted(numbers, reverse=True)) # 输出: [9, 6, 5, 4, 3, 2, 1, 1]
67. staticmethod(function)
将函数转换为静态方法。静态方法不会接收隐式的第一个参数。
# staticmethod() 示例
class MathUtils:
@staticmethod
def add(x, y):
return x + y
@staticmethod
def multiply(x, y):
return x * y
print(MathUtils.add(5, 3)) # 输出: 8
print(MathUtils.multiply(5, 3)) # 输出: 15
68. str(object=‘’)
69. str(object=b’', encoding=‘utf-8’, errors=‘strict’)
返回一个 str 版本的 object。
# str() 示例
print(str(123)) # 输出: '123'
print(str(3.14)) # 输出: '3.14'
print(str([1, 2, 3])) # 输出: '[1, 2, 3]'
print(str(b'hello')) # 输出: "b'hello'"
# 使用编码
print(str(b'hello', encoding='utf-8')) # 输出: 'hello'
70. sum(iterable, start=0)
从 start 开始自左向右对 iterable 的项求和并返回总计值。
# sum() 示例
numbers = [1, 2, 3, 4, 5]
print(sum(numbers)) # 输出: 15
print(sum(numbers, 10)) # 输出: 25 (15 + 10)
# 浮点数求和
floats = [1.1, 2.2, 3.3]
print(sum(floats)) # 输出: 6.6
# 空列表
print(sum([])) # 输出: 0
71. super(type, object_or_type=None)
返回一个代理对象,它会将方法调用委托给 type 的父类或兄弟类。
# super() 示例
class Parent:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hello, I'm {self.name}"
class Child(Parent):
def __init__(self, name, age):
super().__init__(name) # 调用父类的 __init__
self.age = age
def greet(self):
parent_greet = super().greet() # 调用父类的 greet
return f"{parent_greet} and I'm {self.age} years old"
child = Child("Alice", 10)
print(child.greet()) # 输出: Hello, I'm Alice and I'm 10 years old
72. tuple(iterable)
将可迭代对象转换为元组。
# tuple() 示例
print(tuple([1, 2, 3])) # 输出: (1, 2, 3)
print(tuple("hello")) # 输出: ('h', 'e', 'l', 'l', 'o')
print(tuple({1, 2, 3})) # 输出: (1, 2, 3)
print(tuple({"a": 1, "b": 2})) # 输出: ('a', 'b')
73. type(object)
74. type(name, bases, dict)
传入一个参数时,返回 object 的类型。传入三个参数时,返回一个新的类型对象。
# type() 示例
# 一个参数:返回类型
print(type(123)) # 输出: <class 'int'>
print(type("hello")) # 输出: <class 'str'>
print(type([1, 2, 3])) # 输出: <class 'list'>
# 三个参数:创建新类型
MyClass = type('MyClass', (object,), {'x': 42, 'hello': lambda self: "Hello"})
obj = MyClass()
print(obj.x) # 输出: 42
print(obj.hello()) # 输出: Hello
75. vars(object)
返回模块、类、实例或任何其他具有 __dict__
属性的对象的 __dict__
属性。
# vars() 示例
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 30)
print(vars(p)) # 输出: {'name': 'Alice', 'age': 30}
# 无参数时,返回当前局部符号表
def test():
x = 10
y = "hello"
print(vars())
test()
76. zip(*iterables)
创建一个聚合了来自每个可迭代对象中的元素的迭代器。
# zip() 示例
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
cities = ["New York", "London", "Paris"]
# 基本用法
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
# 输出:
# Alice is 25 years old
# Bob is 30 years old
# Charlie is 35 years old
# 多个可迭代对象
for data in zip(names, ages, cities):
print(data)
# 输出:
# ('Alice', 25, 'New York')
# ('Bob', 30, 'London')
# ('Charlie', 35, 'Paris')
# 不等长可迭代对象(以最短的为准)
result = list(zip([1, 2, 3], ['a', 'b']))
print(result) # 输出: [(1, 'a'), (2, 'b')]
77. import(name, globals=None, locals=None, fromlist=(), level=0)
此函数由 import 语句调用,可以直接调用(但不建议)。
# __import__() 示例
# 通常不直接使用,而是使用 import 语句
# 但可以这样使用:
math_module = __import__('math')
print(math_module.sqrt(16)) # 输出: 4.0
# 等同于:
import math
print(math.sqrt(16)) # 输出: 4.0
总结
Python 的内置函数提供了强大而灵活的工具集,涵盖了从基本数学运算到复杂对象操作的各个方面。熟练掌握这些内置函数可以大大提高编程效率和代码质量。
每个内置函数都有其特定的用途和适用场景,理解它们的特性和行为是成为 Python 高手的重要一步。希望本文的详细讲解和代码示例能帮助你更好地理解和使用这些强大的工具。
记住,最好的学习方式是实践,所以不要犹豫,打开你的 Python 解释器,尝试使用这些函数吧!