Home 一文通览Python所有内置函数:提升你的编程效率.md
Post
Cancel

一文通览Python所有内置函数:提升你的编程效率.md

大家好,我是章北海

Python中的内置函数,这些函数覆盖了从基本数据处理到高级编程功能的各种用途。

下面,我将逐一介绍每个函数的用途和提供相应的代码示例。

A

  • abs():返回数字的绝对值。
    1
    
    print(abs(-5))  # 输出: 5
    
  • aiter():返回异步迭代器。
    1
    2
    3
    4
    5
    
    async def async_iter():
        for i in range(3):
            yield i
    async for value in aiter(async_iter()):
        print(value)  # 输出: 0, 1, 2
    
  • all():判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE。
    1
    
    print(all([True, True, True]))  # 输出: True
    
  • any():判断给定的可迭代参数 iterable 是否有任一元素为 TRUE。
    1
    
    print(any([False, True, False]))  # 输出: True
    
  • anext():返回异步迭代器的下一个元素。
    1
    2
    3
    4
    5
    
    async def async_iter():
        for i in range(3):
            yield i
    aiter_obj = aiter(async_iter())
    print(await anext(aiter_obj))  # 输出: 0
    
  • ascii():返回对象的可打印表示形式,其中非 ASCII 字符通过 \x, \u 或 \U 编码。
    1
    
    print(ascii("你好"))  # 输出: '\u4f60\u597d'
    

B

  • bin():将整数转换成前缀为“0b”的二进制字符串。
    1
    
    print(bin(10))  # 输出: '0b1010'
    
  • bool():将给定参数转换成布尔类型。
    1
    
    print(bool(0))  # 输出: False
    
  • breakpoint():调用此函数将触发一个断点。
    1
    
    # breakpoint()
    
  • bytearray():返回一个新的字节数组。
    1
    
    print(bytearray([1, 2, 3]))  # 输出: bytearray(b'\x01\x02\x03')
    
  • bytes():返回一个新的字节序列对象。
    1
    
    print(bytes([1, 2, 3]))  # 输出: b'\x01\x02\x03'
    

C

  • callable():检查对象是否可调用。
    1
    2
    3
    
    def func():
        return "Hello"
    print(callable(func))  # 输出: True
    
  • chr():返回对应于整数 i 的 ASCII 字符。
    1
    
    print(chr(97))  # 输出: 'a'
    
  • classmethod():把一个方法声明为类的方法。
    1
    2
    3
    4
    5
    
    class C:
        @classmethod
        def f(cls):
            print(cls.__name__)
    C.f()  # 输出: 'C'
    
  • compile():将源字符串编译成代码或 AST 对象。
    1
    2
    
    code = compile('print(42)', '', 'exec')
    exec(code)  # 输出: 42
    
  • complex():创建一个复数。
    1
    
    print(complex(1, 2))  # 输出: (1+2j)
    

D

  • delattr():删除对象的属性。
    1
    2
    3
    4
    
    class Person:
        name = "John"
    delattr(Person, 'name')
    # print(Person.name)  # 将引发 AttributeError
    
  • dict():创建数据字典。
    1
    
    print(dict(a=1, b=2))  # 输出: {'a': 1, 'b': 2}
    
  • dir():尝试返回对象的属性列表。
    1
    
    print(dir([1, 2, 3]))  # 输出包括: ['append', 'count', 'extend', ...]
    
  • divmod():返回包含商和余数的元组。
    1
    
    print(divmod(7, 2))  # 输出: (3, 1)
    

E

  • enumerate():将一个可遍历的数据对象组合为一个索引序列,同时列出数据和数据下标。
    1
    2
    
    for index, value in enumerate(['a', 'b', 'c']):
        print(index, value)  # 输出: 0 a, 1 b, 2 c
    
  • eval():执行一个字符串表达式,并返回表达式的值。
    1
    
    print(eval('3 + 4'))  # 输出: 7
    
  • exec():执行动态Python代码。
    1
    
    exec('print("Hello World")')  # 输出: Hello World
    

F

  • filter():使用指定方法过滤序列。
    1
    2
    3
    
    numbers = [1, 2, 3, 4]
    even = filter(lambda x: x % 2 == 0, numbers)
    print(list(even))  # 输出: [2, 4]
    
  • float():将一个字符串或数字转换为浮点数。
    1
    
    print(float("10.5"))  # 输出: 10.5
    
  • format():格式化输出字符串。
    1
    
    print(format(0.5, '%'))  # 输出: '50.000000%'
    
  • frozenset():创建一个不可变集合。
    1
    
    print(frozenset([1, 2, 3]))  # 输出: frozenset({1, 2, 3})
    

G

  • getattr():获取对象的属性。
    1
    2
    3
    
    class Person:
        name = "John"
    print(getattr(Person, 'name'))  # 输出: John
    
  • globals():返回当前全局符号表的字典。
    1
    
    print(globals())  # 输出包含当前全局变量的字典
    

H

  • hasattr():判断对象是否包含对应的属性。
    1
    2
    3
    
    class Person:
        name = "John"
    print(hasattr(Person, 'name'))  # 输出: True
    
  • hash():返回对象的哈希值。
    1
    
    print(hash("test"))  # 输出: 哈希值
    
  • help():调用内置的帮助系统。
    1
    
    # help()  # 交互式帮助
    
  • hex():将整数转换成前缀为“0x”的十六进制字符串。
    1
    
    print(hex(255))  # 输出: '0xff'
    

I

  • id():返回对象的唯一标识符。
    1
    2
    
    obj = object()
    print(id(obj))  # 输出: 对象的内存地址
    
  • input():接收输入。
    1
    
    # name = input("Enter your name: ")
    
  • int():将一个字符串或数字转换为整数。
    1
    
    print(int("10"))  # 输出: 10
    
  • isinstance():检查对象是否为指定类的实例。
    1
    
    print(isinstance(5, int))  # 输出: True
    
  • issubclass():检查一个类是否是另一个类的子类。
    1
    2
    3
    4
    5
    
    class A:
        pass
    class B(A):
        pass
    print(issubclass(B, A))  # 输出: True
    
  • iter():返回迭代器。
    1
    2
    
    i = iter([1, 2, 3])
    print(next(i))  # 输出: 1
    

L

  • len():返回对象的长度或项目数。
    1
    
    print(len([1, 2, 3]))  # 输出: 3
    
  • list():将一个可迭代的对象转换为列表。
    1
    
    print(list((1, 2, 3)))  # 输出: [1, 2, 3]
    
  • locals():返回当前局部符号表的字典。
    1
    2
    3
    4
    
    def func():
        a = 1
        print(locals())  # 输出: {'a': 1}
    func()
    

M

  • map():对指定序列做映射。
    1
    2
    3
    4
    5
    
    def square(x):
        return x ` 2
    numbers = [1, 2, 3, 4]
    squares = map(square, numbers)
    print(list(squares))  # 输出: [1, 4, 9, 16]
    
  • max():返回最大值。
    1
    
    print(max([1, 2, 3]))  # 输出: 3
    
  • memoryview():返回给定参数的内存查看对象。
    1
    2
    3
    
    bytes_obj = bytes([1, 2, 3])
    mv = memoryview(bytes_obj)
    print(mv[1])  # 输出: 2
    
  • min():返回最小值。
    1
    
    print(min([1, 2, 3]))  # 输出: 1
    

N

  • next():返回迭代器的下一个项目。
    1
    2
    
    it = iter([1, 2, 3])
    print(next(it))  # 输出: 1
    

O

  • object():返回一个新的无特征对象。
    1
    2
    
    obj = object()
    print(type(obj))  # 输出: <class 'object'>
    
  • oct():将整数转换成前缀为“0o”的八进制字符串。
    1
    
    print(oct(8))  # 输出: '0o10'
    
  • open():打开一个文件,并返回对应的文件对象。
    1
    
    # f = open("test.txt", "r")
    
  • ord():返回对应字符的 ASCII 数值,或者 Unicode 数值。
    1
    
    print(ord('a'))  # 输出: 97
    

P

  • pow():计算 x 的 y 次方。
    1
    
    print(pow(2, 3))  # 输出: 8
    
  • print():打印指定的文字或变量的值。
    1
    
    print("Hello, world!")  # 输出: Hello, world!
    
  • property():在新式类中返回属性值。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
    class C:
        def __init__(self, x):
            self._x = x
        def getx(self):
            return self._x
        def setx(self, value):
            self._x = value
        def delx(self):
            del self._x
        x = property(getx, setx, delx, "I'm the 'x' property.")
    c = C(123)
    print(c.x)  # 输出: 123
    c.x = 456
    print(c.x)  # 输出: 456
    

R

  • range():生成一个数字序列。
    1
    2
    
    for i in range(5):
        print(i)  # 输出: 0, 1, 2, 3, 4
    
  • repr():返回对象的字符串表示。
    1
    2
    
    s = "Hello, world!"
    print(repr(s))  # 输出: 'Hello, world!'
    
  • reversed():返回一个反向的迭代器。
    1
    2
    
    for i in reversed([1, 2, 3]):
        print(i)  # 输出: 3, 2, 1
    
  • round():四舍五入,返回浮点数 x 的四舍五入值。
    1
    
    print(round(3.14159, 2))  # 输出: 3.14
    

S

  • set():创建一个无序不重复元素集。
    1
    
    print(set([1, 2, 2, 3]))  # 输出: {1, 2, 3}
    
  • setattr():设置属性值。
    1
    2
    3
    4
    
    class Person:
        name = "John"
    setattr(Person, 'age', 30)
    print(Person.age)  # 输出: 30
    
  • slice():返回一个切片对象。
    1
    2
    3
    
    lst = [1, 2, 3, 4, 5]
    sl = slice(1, 4)
    print(lst[sl])  # 输出: [2, 3, 4]
    
  • sorted():返回已排序的列表。
    1
    
    print(sorted([3, 1, 2]))  # 输出: [1, 2, 3]
    
  • staticmethod():创建静态方法。
    1
    2
    3
    4
    5
    
    class C:
        @staticmethod
        def f():
            print('static method')
    C.f()  # 输出: 'static method'
    
  • str():将对象转换为字符串。
    1
    
    print(str(123))  # 输出: '123'
    
  • sum():计算输入的数字的总和。
    1
    
    print(sum([1, 2, 3]))  # 输出: 6
    
  • super():用于调用父类(超类)的一个方法。
    1
    2
    3
    4
    5
    6
    7
    8
    
    class Base:
        def __init__(self):
            print("Base init")
    class Derived(Base):
        def __init__(self):
            super().__init__()
            print("Derived init")
    Derived()  # 输出: Base init, Derived init
    

T

  • tuple():将一个可迭代系列转换为元组。
    1
    
    print(tuple([1, 2, 3]))  # 输出: (1, 2, 3)
    
  • type():返回对象的类型。
    1
    
    print(type(123))  # 输出: <class 'int'>
    

V

  • vars():返回对象的 dict 属性。
    1
    2
    3
    4
    5
    
    class Person:
        def __init__(self, name):
            self.name = name
    p = Person("John")
    print(vars(p))  # 输出: {'name': 'John'}
    

Z

  • zip():将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
    1
    2
    3
    4
    
    a = [1, 2, 3]
    b = [4, 5, 6]
    zipped = zip(a, b)
    print(list(zipped))  # 输出: [(1, 4), (2, 5), (3, 6)]
    

_

  • __import__():这是一个高级函数,用于动态导入模块。
    1
    2
    
    math = __import__('math')
    print(math.sqrt(16))  # 输出: 4.0
    

以上就是Python内置函数的简要介绍和示例。

这些函数为Python编程提供了强大的支持,使得各种操作更加便捷。

This post is licensed under CC BY 4.0 by the author.