Python常用的内置函数


以下是 Python 3.12 所有内置函数的详细介绍,包括用法和示例代码:



1. abs()

返回数字的绝对值。

print(abs(-10))  # 10
print(abs(3.5))  # 3.5


2. all()

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

print(all([True, 1, "non-empty"]))  # True
print(all([True, 0, "non-empty"]))  # False


3. any()

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

print(any([False, 0, "non-empty"]))  # True
print(any([False, 0, None]))         # False


4. ascii()

返回字符串的可打印表示,非 ASCII 字符会被转义。

print(ascii('你好'))  # '\u4f60\u597d'


5. bin()

返回一个整数的二进制表示形式(以 0b 开头的字符串)。

print(bin(10))  # '0b1010'


6. bool()

将值转换为布尔类型。

print(bool(0))  # False
print(bool(1))  # True


7. breakpoint()

启动调试器,默认是 PDB。

breakpoint()  # 启动调试模式


8. bytearray()

返回一个可变的字节数组。

ba = bytearray('hello', 'utf-8')
print(ba)  # bytearray(b'hello')


9. bytes()

返回不可变的字节对象。

b = bytes('hello', 'utf-8')
print(b)  # b'hello'


10. callable()

判断对象是否可调用。

def func():
    pass

print(callable(func))  # True
print(callable(123))   # False


11. chr()

返回指定 Unicode 编码对应的字符。

print(chr(97))  # 'a'
print(chr(8364))  # '€'


12. classmethod()

将函数变为类方法,类方法第一个参数是类本身。

class MyClass:
    @classmethod
    def greet(cls):
        return f"Hello from {cls}"

print(MyClass.greet())  # "Hello from <class '__main__.MyClass'>"


13. compile()

将字符串或代码对象编译为字节代码,可以执行。

code = "x = 5\ny = 10\nprint(x + y)"
compiled_code = compile(code, '<string>', 'exec')
exec(compiled_code)  # 输出: 15


14. complex()

创建一个复数。

print(complex(1, 2))  # (1+2j)


15. delattr()

删除对象的属性。

class MyClass:
    attr = 10

obj = MyClass()
delattr(obj, 'attr')


16. dir()

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

print(dir([]))  # ['append', 'clear', ...]


17. divmod()

返回两个数的商和余数。

print(divmod(10, 3))  # (3, 1)


18. enumerate()

为可迭代对象添加索引。

for index, value in enumerate(['a', 'b', 'c']):
    print(index, value)


19. eval()

动态执行字符串表达式。

x = 10
print(eval("x + 5"))  # 15


20. exec()

动态执行代码块。

exec("""
for i in range(3):
    print(i)
""")


21. filter()

过滤符合条件的元素。

nums = [1, 2, 3, 4]
filtered = filter(lambda x: x % 2 == 0, nums)
print(list(filtered))  # [2, 4]


22. float()

将值转换为浮点数。

print(float(10))  # 10.0


23. format()

格式化值为指定格式。

print(format(1234.5678, ",.2f"))  # '1,234.57'


24. frozenset()

返回不可变集合。

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


25. getattr()

获取对象的属性值。

class MyClass:
    attr = 10

obj = MyClass()
print(getattr(obj, 'attr'))  # 10


26. globals()

返回当前全局命名空间的字典。

print(globals())


27. hasattr()

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

class MyClass:
    attr = 10

obj = MyClass()
print(hasattr(obj, 'attr'))  # True

以下是 Python 3.12 内置函数的后续详细介绍:



28. hash()

返回对象的哈希值(整数)。仅适用于可哈希对象(如数字、字符串、元组等)。

print(hash('hello'))  # 输出一个整数
print(hash(12345))    # 输出一个整数


29. help()

启动内置帮助系统,或者输出对象的帮助信息。

help(str)  # 输出字符串类的帮助信息
help(len)  # 输出 len() 函数的帮助


30. hex()

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

print(hex(255))  # '0xff'
print(hex(16))   # '0x10'


31. id()

返回对象的唯一标识(内存地址)。

x = 10
print(id(x))  # 输出对象的内存地址


32. input()

从用户输入读取一行。

name = input("What's your name? ")
print(f"Hello, {name}!")


33. int()

将值转换为整数,支持进制转换。

print(int("42"))        # 42
print(int("101", 2))    # 5(二进制转十进制)


34. isinstance()

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

print(isinstance(10, int))  # True
print(isinstance("abc", str))  # True


35. issubclass()

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

class A:
    pass

class B(A):
    pass

print(issubclass(B, A))  # True
print(issubclass(A, B))  # False


36. iter()

返回一个迭代器。

nums = [1, 2, 3]
it = iter(nums)
print(next(it))  # 1
print(next(it))  # 2


37. len()

返回对象的长度(元素个数)。

print(len([1, 2, 3]))  # 3
print(len("hello"))    # 5


38. list()

将对象转换为列表。

print(list("abc"))  # ['a', 'b', 'c']


39. locals()

返回当前局部命名空间的字典。

def func():
    a = 10
    b = 20
    print(locals())

func()  # {'a': 10, 'b': 20}


40. map()

将函数应用于可迭代对象的每个元素,并返回结果的迭代器。

nums = [1, 2, 3]
squared = map(lambda x: x**2, nums)
print(list(squared))  # [1, 4, 9]


41. max()

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

print(max([1, 2, 3]))  # 3
print(max(1, 2, 3))    # 3


42. min()

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

print(min([1, 2, 3]))  # 1
print(min(1, 2, 3))    # 1


43. next()

获取迭代器的下一个元素。

it = iter([1, 2, 3])
print(next(it))  # 1
print(next(it))  # 2


44. object()

返回一个新的空对象。

obj = object()
print(obj)  # <object object at ...>


45. oct()

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

print(oct(8))  # '0o10'


46. open()

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

with open('example.txt', 'w') as file:
    file.write("Hello, world!")


47. ord()

返回字符的 Unicode 编码值。

print(ord('a'))  # 97
print(ord('€'))  # 8364


48. pow()

计算幂(x**y)并对结果取模(可选)。

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. range()

生成一个整数序列。

for i in range(5):
    print(i)  # 0, 1, 2, 3, 4


52. repr()

返回对象的字符串表示(便于调试)。

print(repr("hello"))  # "'hello'"


53. reversed()

返回一个反向迭代器。

nums = [1, 2, 3]
print(list(reversed(nums)))  # [3, 2, 1]


54. round()

返回四舍五入的值。

print(round(3.14159, 2))  # 3.14


55. set()

返回一个集合。

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


56. setattr()

设置对象属性。

class MyClass:
    pass

obj = MyClass()
setattr(obj, 'attr', 10)
print(obj.attr)  # 10


57. slice()

创建一个切片对象。

s = slice(1, 5, 2)
print([1, 2, 3, 4, 5][s])  # [2, 4]


58. sorted()

返回排序后的列表。

nums = [3, 1, 4, 1]
print(sorted(nums))  # [1, 1, 3, 4]


59. staticmethod()

将函数变为静态方法。

class MyClass:
    @staticmethod
    def greet():
        return "Hello, world!"

print(MyClass.greet())  # "Hello, world!"


60. str()

将对象转换为字符串。

print(str(123))  # "123"

以下是 Python 3.12 内置函数的剩余部分介绍:



61. sum()

计算可迭代对象中所有元素的和,支持起始值。

print(sum([1, 2, 3]))        # 6
print(sum([1, 2, 3], 10))   # 16(加上起始值 10)


62. super()

返回父类的一个代理对象,用于访问父类的方法或属性。

class Parent:
    def greet(self):
        return "Hello from Parent!"

class Child(Parent):
    def greet(self):
        return super().greet() + " And hello from Child!"

obj = Child()
print(obj.greet())  # "Hello from Parent! And hello from Child!"


63. tuple()

将可迭代对象转换为元组。

print(tuple([1, 2, 3]))  # (1, 2, 3)


64. type()

返回对象的类型,或者动态创建新类。

print(type(10))  # <class 'int'>

# 动态创建类
MyClass = type('MyClass', (), {'attr': 10})
obj = MyClass()
print(obj.attr)  # 10


65. vars()

返回对象的 __dict__ 属性(用于存储对象的可变属性)。

class MyClass:
    def __init__(self):
        self.attr = 10

obj = MyClass()
print(vars(obj))  # {'attr': 10}


66. zip()

将多个可迭代对象“压缩”成一个元组迭代器。

a = [1, 2, 3]
b = ['a', 'b', 'c']
zipped = zip(a, b)
print(list(zipped))  # [(1, 'a'), (2, 'b'), (3, 'c')]


67. import()

用于动态导入模块。通常使用 importlib.import_module() 替代。

math_module = __import__('math')
print(math_module.sqrt(16))  # 4.0


68. format()

将值格式化为字符串。

print(format(12345, ',d'))  # "12,345"(千位分隔符)
print(format(3.14159, '.2f'))  # "3.14"


69. globals()

返回全局命名空间的字典。

a = 10
print(globals()['a'])  # 10


70. callable()

检查对象是否可调用(如函数或定义了 __call__ 的类实例)。

print(callable(len))  # True
print(callable(10))   # False


71. delattr()

删除对象的指定属性。

class MyClass:
    def __init__(self):
        self.attr = 10

obj = MyClass()
delattr(obj, 'attr')
print(hasattr(obj, 'attr'))  # False


72. dir()

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

print(dir([]))  # 列出列表对象的所有属性和方法


73. eval()

执行字符串形式的 Python 表达式(注意安全性问题)。

expr = "2 + 3"
print(eval(expr))  # 5


74. exec()

执行字符串形式的 Python 代码。

code = """
def add(a, b):
    return a + b
print(add(2, 3))
"""
exec(code)  # 输出 5


75. filter()

筛选可迭代对象中满足条件的元素。

nums = [1, 2, 3, 4, 5]
filtered = filter(lambda x: x % 2 == 0, nums)
print(list(filtered))  # [2, 4]


76. frozenset()

返回一个不可变集合。

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


77. getattr()

获取对象的指定属性值。

class MyClass:
    attr = 10

obj = MyClass()
print(getattr(obj, 'attr'))  # 10


78. hasattr()

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

class MyClass:
    attr = 10

obj = MyClass()
print(hasattr(obj, 'attr'))  # True


79. memoryview()

返回支持缓冲区协议对象的“内存视图”。

data = bytearray(b'hello')
mv = memoryview(data)
print(mv[0])  # 104(对应字母 'h' 的 ASCII 值)


80. slice()

创建一个切片对象。

s = slice(1, 5, 2)
lst = [1, 2, 3, 4, 5]
print(lst[s])  # [2, 4]


81. compile()

将字符串编译为代码对象,可用于 exec()eval()

code = "print('Hello, world!')"
compiled_code = compile(code, '<string>', 'exec')
exec(compiled_code)  # 输出 "Hello, world!"


至此,Python 3.12 的所有内置函数已介绍完成!如果有任何特定函数需要更详细的说明或示例,请随时告诉我!

文章标签:

评论(0)