Python 内置函数汇总(使用示例)

  1. abs( number )

    求解整数,浮点数绝对值,返回复数模大小

  2. aiter()

    异步的方式遍历可迭代对象的异步迭代器

    import asyncio
    
    count = 0
    
    async def example():
        async def async_generator():
            global count
            while True:
                count += 1
                print(f"count:{count}")
                yield count
    
    
        async_iterable = async_generator()
        async_iterator = aiter(async_iterable)
        for _ in range(3):
            value = await async_iterator.__anext__()
            print(value)
    
    asyncio.run(example())
    #####
    count:1
    1
    count:2
    2
    count:3
    3
    
  3. all(iterable)

    可迭代对象所有元素是为真则返回 true

    print(all([])) # true
    print(all([1,2,0])) # false
    print(all((1,2,True,"23"))) # true
    
    
  4. any(iterable)

    可迭代对象任何一个元素为真则返回 true

    print(any([])) # False
    print(any([0,0])) # False
    print(any([1,2,0])) # True
    print(any((1,2,True,"23"))) # True
    
  5. ascii(object)
    将对象转换为 ASCII 字符串表示,对于非 ASCII 字符,会使用Unicode 转义序列来表示

    print(ascii(object))
    print(ascii("\r\n2345你好"))
    print(ascii("Hello-你好呀"))
    
    <class 'object'>
    '\r\n2345\u4f60\u597d'
    'Hello-\u4f60\u597d\u5440'
    
  6. bin(x)

    将一个整数转换为带前缀 “0b” 的二进制数字符串

    print(bin(12))
    print(bin(-2))
    print(format(14, '#b'), format(14, 'b'))
    # 0b1100
    # -0b10
    # 0b1110 1110
    
  7. bool(x)

    返回真假值

    print(bool(0))
    print(bool(""))
    print(bool(None))
    print(bool(False))
    print(bool(True))
    print(bool("324"))
    
    # False
    # False
    # False
    # False
    # True
    # True
    
  8. breakpoint()
    添加调试断点

    def add_numbers(a, b):
        result = a + b
        breakpoint() # 断点
        return result
    
    print(add_numbers(3, 5))
    
    # > d:\a-xhspro\tk\pytest\test.py(71)add_numbers()
    # -> return result
    # (Pdb) help
    # 
    # Documented commands (type help <topic>):
    # ========================================
    # EOF    c          d        h         list      q        rv       undisplay
    # a      cl         debug    help      ll        quit     s        unt      
    # alias  clear      disable  ignore    longlist  r        source   until    
    # args   commands   display  interact  n         restart  step     up       
    # b      condition  down     j         next      return   tbreak   w        
    # break  cont       enable   jump      p         retval   u        whatis   
    # bt     continue   exit     l         pp        run      unalias  where    
    # 
    # Miscellaneous help topics:
    # ==========================
    # exec  pdb
    # (Pdb) result
    # 8
    # (Pdb) a
    # a = 3
    # b = 5
    # (Pdb) continue
    # 8
    # 
    # Process finished with exit code 0
    
  9. bytearray(source, encoding, errors)
    创建一个新的字节数组,source:可以是以下几种类型之一:
    一个整数,表示字节数组的初始大小,此时创建的字节数组将被初始化为零值。
    一个可迭代对象,其元素是整数,范围在 0 到 255 之间,表示字节值。
    一个字节字符串(bytes对象),字节数组将从这个字节字符串复制初始化。
    encoding(可选):如果source是一个字符串,这个参数指定字符串的编码方式。
    errors(可选):如果在编码过程中出现错误,这个参数指定如何处理错误。

    print(bytearray(5))
    print(bytearray([65,66,67]))
    print(bytearray("Hello", encoding="utf-8"))
    # bytearray(b'\x00\x00\x00\x00\x00')
    # bytearray(b'ABC')
    # bytearray(b'Hello')
    
  10. bytes(source, encoding, errors)
    创建一个新的字节对象,参数与 bytearray 一样

    print(bytes(5))
    print(bytes([65,66,67]))
    print(bytes("Hello", encoding="utf-8"))
    # b'\x00\x00\x00\x00\x00'
    # b'ABC'
    # b'Hello'
    
    
  11. callable(object)
    判断对象是否可调用,实例所属的类有 __call__() 方法,类本身在 Python 中默认是可调用的(通过实例化创建对象)

    class A:
        def __call__(self, *args, **kwargs):
            print("yes")
    
    class B:
        pass
    
    print(callable(bytearray))
    print(callable(1))
    print(callable(A))
    print(callable(B))
    
    print(dir(1))
    print(dir(A))
    print(dir(B))
    
    # True
    # False
    # True
    # True
    # ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_count', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
    # ['__call__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
    # ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
    
    
  12. chr(i) 与 ord(x)
    返回 Unicode 码位为整数 i 的字符的字符串格式。

    print(chr(1234))
    print(chr(199))
    print(ord("Ӓ"))
    print(ord("Ç"))
    # Ӓ
    # Ç
    # 1234
    # 199
    
  13. @classmethod

    把一个方法封装成类方法。

    class A:
        @classmethod
        def add(self, a):
            print(a+9)
    A.add(1)
    A().add(1)
    # 10
    # 10
    
  14. compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
    将源代码编译为代码对象,这个代码对象可以被exec()eval()函数执行。

    source:可以是字符串、字节对象或抽象语法树对象,表示要编译的源代码。
    filename:指定源代码的文件名,这主要用于在错误消息中提供上下文信息。
    mode:指定编译的模式,可以是’exec’(用于编译多条语句,如模块或脚本)、‘eval’(用于编译单个表达式)或’single’(用于编译单个交互语句)。
    flags(可选):影响编译过程的标志,默认为 0。可以使用位运算符组合不同的标志。
    dont_inherit(可选):决定是否继承当前环境的编译标志,默认为False。
    optimize(可选):指定优化级别,默认为 -1,表示使用默认的优化级别。

    source_code = "print('Hello, World!')"
    compiled_code = compile(source_code, "<string>", "exec")
    compiled_code2 = compile(source_code, "<string>", "eval")
    exec(compiled_code)
    eval(compiled_code2)
    # Hello, World!
    # Hello, World!
    
  15. complex(real=0, imag=0)

    将特定的字符串或数字转换为一个复数,或基于特定的实部和虚部创建一个复数。

    print(complex('+1.23'))
    print(complex('-4.5j'))
    print(complex('-1.23+4.5j'))
    print(complex('\t( -1.23+4.5J )\n'))
    print(complex('-Infinity+NaNj'))
    print(complex(1.23))
    print(complex(imag=-4.5, real=2))
    print(complex(-1.23, 4.5))
    
    # (1.23+0j)
    # -4.5j
    # (-1.23+4.5j)
    # (-1.23+4.5j)
    # (-inf+nanj)
    # (1.23+0j)
    # (2-4.5j)
    # (-1.23+4.5j)
    
  16. delattr(object, name)

    这是 setattr() 的相关函数。 其参数是一个对象和一个字符串。 其中字符串必须是对象的某个属性的名称。 该函数会删除指定的属性,如果对象允许这样做的话。 例如,delattr(x, 'foobar') 等价于 del x.foobar

    class A:
        def __init__(self):
            self.test_name = "3245"
            self.test_num = 12
    
        def test_fun(self):
            try:
                print(self.test_num)
            except AttributeError as e:
                print(e)
    
            try:
                print(self.test_name)
            except AttributeError as e:
                print(e)
    
    a = A()
    a.test_fun()
    # 12
    # 3245
    
    delattr(a,"test_name")
    a.test_fun()
    # 12
    # 'A' object has no attribute 'test_name'
    del a.test_num
    a.test_fun()
    # 'A' object has no attribute 'test_num'
    # 'A' object has no attribute 'test_name'
    
    
  17. class dict(iterable, **kwarg)

    创建一个新的字典。dict 对象是一个字典类。

    print(dict([('a', 1), ('b', 2), ('c', 3), ('a', 23)]))
    print(dict(key1='value1', key2='value2'))
    
    # {'a': 23, 'b': 2, 'c': 3}
    # {'key1': 'value1', 'key2': 'value2'}
    
  18. dir(object)

    如果没有实参,则返回当前本地作用域中的名称列表。如果有实参,它会尝试返回该对象的有效属性列表。如果对象未提供 __dir__(),该函数会尽量从对象所定义的 __dict__ 属性和其类型对象中收集信息。 结果列表不一定是完整的,并且当对象具有自定义的 __getattr__() 时还可能是不准确的。

    print(dir())
    print(dir(int))
    
    # ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
    # ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_count', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
    
    class Shape:
        def __dir__(self):
            return ['area', 'perimeter', 'location']
    
    s = Shape()
    print(dir(s))
    # ['area', 'location', 'perimeter']
    
  19. divmod(a, b)

    接受两个(非复数)数字作为参数并返回由当对其使用整数除法时的商和余数组成的数字对。 在混用不同的操作数类型时,则会应用二元算术运算符的规则。 对于整数来说,结果与 (a // b, a % b) 相同。 对于浮点数来说则结果为 (q, a % b),其中 q 通常为 math.floor(a / b) 但可能会比它小 1。 在任何情况下 q * b + a % b 都非常接近 a,如果 a % b 为非零值则它将具有与 b 相同的正负号,并且 0 <= abs(a % b) < abs(b)

    print(divmod(4,2))
    print(divmod(4.0, 0.4))
    # (2, 0)
    # (9.0, 0.3999999999999998)
    
  20. enumerate(iterable, start=0)

    返回一个枚举对象。iterable 必须是一个序列,或 iterator,或其他支持迭代的对象。

    print(list(enumerate([1,2,3,4])))
    print(list(enumerate([1,2,3,4], 2)))
    
    # [(0, 1), (1, 2), (2, 3), (3, 4)]
    # [(2, 1), (3, 2), (4, 3), (5, 4)]
    
  21. eval(expression, globals=None, locals=None)

    exec(object, globals=None, locals=None, /, ***, closure=None)
    exec() 函数支持语句的动态执行。 globals()locals() 函数分别返回当前的全局和本地字典,可供传给 eval()exec() 使用。

  22. filter(function, iterable)

    使用 iterablefunction 返回真值的元素构造一个迭代器。 iterable 可以是一个序列,一个支持迭代的容器或者一个迭代器。 如果 functionNone,则会使用标识号函数,也就是说,iterable 中所有具有假值的元素都将被移除。

    iter_a = filter(lambda x:x>3, [1,2,3,4,2,143,223])
    print([x for x in iter_a])
    iter_b = filter(None, [1,2,3,4,False,0,223])
    print([x for x in iter_b])
    
    # [4, 143, 223]
    # [1, 2, 3, 4, 223]
    
  23. class float(string, /)

    返回基于一个数字或字符串构建的浮点数。

    x = [float('+1.23'),float('   -12345\n'),float('1e-003'),float('+1E6'),float('-Infinity')]
    print(x)
    # [1.23, -12345.0, 0.001, 1000000.0, -inf]
    
  24. format(value, format_spec=‘’)

    value 转换为“格式化后”的形式,格式由 format_spec 进行控制。

    print(format(42, '>5d'))    # 右对齐
    print(format(42, '<5d'))    # 左对齐
    print(format(42, '^5d'))    # 居中
    #    42
    # 42
    #  42
    
    print(format(42, 'b'))    # 二进制
    print(format(42, 'o'))    # 八进制
    print(format(42, 'x'))    # 十六进制
    print(format(42, 'X'))    # 十六进制
    # 101010
    # 52
    # 2a
    # 2A
    
    print(format(3.14159, '.2f'))    # 保留两位小数,四舍五入
    # 3.14
    print(format(1.23456, '.3f'))    # 保留三位小数
    # 1.235
    print(format(123456789, '.2e'))    # 两位小数科学计数法
    print(format(1234567.89, ',.2f'))    # 千位分隔
    # 1.23e+08
    # 1,234,567.89
    print(format('Hello', '>10s'))    # 右对齐
    print(format('Hello', '<10s'))    # 左对齐
    print(format('Hello', '^10s'))    # 居中
    print(format('Hello', '=>10s'))    # 填充 =
    print(format('Hello World', '10.5s'))    # 截断为长度为 5 的字符串,并填充到宽度为 10
    #      Hello
    # Hello
    #   Hello
    # =====Hello
    # Hello
    
    data = {'name': 'John', 'age': 30}
    print('{name} is {age} years old.'.format(**data))    # 十六进制
    
    data = {'price': 123.45}
    print('The price is {price:.2f}.'.format(**data))    # 十六进制
    # John is 30 years old.
    # The price is 123.45.
    
  25. frozenset(iterable=set())

    返回一个新的 frozenset 对象,它包含可选参数 iterable 中的元素。类似集合,

    不可变性,集合操作。

    set_a = frozenset([1,23,4,2,788])
    set_b = frozenset([1,23,7,2, 0])
    print(set_a)
    print(set_a | set_b)
    print(set_a & set_b)
    print(set_a - set_b) 
    
    # frozenset({1, 2, 4, 788, 23})
    # frozenset({0, 1, 2, 4, 7, 788, 23})
    # frozenset({1, 2, 23})
    # frozenset({4, 788})
    
  26. getattr(object, name, default)
    object 中指定名称的属性的值。 name 必须是字符串。 如果该字符串是对象的某一属性的名称,则结果将为该属性的值。

    class A():
        def __init__(self):
            self.name = "wsd"
            self.age = 12
    
    print(getattr(A(), "name"))
    print(getattr(A(), "age"))
    
    # wsd
    # 12
    
  27. globals()
    返回实现当前模块命名空间的字典。对于函数内的代码,这是在定义函数时设置的,无论函数在哪里被调用都保持不变。

    print(globals())
    
    {'__name__': '__main__', '__doc__': '\n@FileName:test.py\n@Description:\n@Author:锦沐Python\n@Time:2024/9/10 18:22\n', '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000019D7B6B4790>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:\\A-XHSPro\\Tk\\Pytest\\test.py', '__cached__': None, 'A': <class '__main__.A'>}
    
  28. hasattr(object, name)

    该实参是一个对象和一个字符串。如果字符串是对象的属性之一的名称,则返回 True,否则返回 False

    class A():
        def __init__(self):
            self.name = "wsd"
            self.age = 12
    
    print(hasattr(A(), "name"))
    print(hasattr(A(), "name1")) 
    # True
    # False
    
  29. hash(object)

    返回该对象的哈希值(如果它有的话)。哈希值是整数。它们在字典查找元素时用来快速比较字典的键。

    print(hash(1))
    print(hash(1.0))
    print(hash("123"))
    print(hash((1,2,3)))
    # 1
    # 1
    # 5228794447094413867
    # 529344067295497451
    
  30. help(request)

    启动内置的帮助系统(此函数主要在交互式中使用)。如果没有实参,解释器控制台里会启动交互式帮助系统。如果实参是一个字符串,则在模块、函数、类、方法、关键字或文档主题中搜索该字符串,并在控制台上打印帮助信息。如果实参是其他任意对象,则会生成该对象的帮助页。

    class A():
        """
        this is a test class
        """
        def __init__(self):
            self.name = "wsd"
            self.age = 12
    help(list)
    
    help(A)
    
    help("re")
    
    Help on class list in module builtins:
    class list(object)
     |  list(iterable=(), /)
     |  
     |  Built-in mutable sequence.
     |  
     |  If no argument is given, the constructor creates a new empty list.
     |  The argument must be an iterable if specified.
     |  
     |  Methods defined here:
     |  append(self, object, /)
     |      Append object to the end of the list.
     |  
     |  clear(self, /)
     |      Remove all items from list.
     |  
     |  copy(self, /)
     |      Return a shallow copy of the list.
    ......
    
    Help on class A in module __main__:
    
    class A(builtins.object)
     |  this is a test class
     |  
     |  Methods defined here:
     |  
     |  __init__(self)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
    
    Help on module re:
    
    NAME
        re - Support for regular expressions (RE).
    
    MODULE REFERENCE
        https://docs.python.org/3.10/library/re.html
        
        The following documentation is automatically generated from the Python
        source files.  It may be incomplete, incorrect or include features that
        are considered implementation detail and may vary between Python
        implementations.  When in doubt, consult the module reference at the
        location listed above.
    
    DESCRIPTION
        This module provides regular expression matching operations similar to
        those found in Perl.  It supports both 8-bit and Unicode strings; both
        the pattern and the strings being processed can contain null bytes and
        characters outside the US ASCII range.
        
        Regular expressions can contain both special and ordinary characters.
        Most ordinary characters, like "A", "a", or "0", are the simplest
        regular expressions; they simply match themselves.  You can
        concatenate ordinary characters, so last matches the string 'last'.
        
        The special characters are:
            "."      Matches any character except a newline.
            "^"      Matches the start of the string.
            "$"      Matches the end of the string or just before the newline at
                     the end of the string.
            "*"      Matches 0 or more (greedy) repetitions of the preceding RE.
                     Greedy means that it will match as many repetitions as possible.
            "+"      Matches 1 or more (greedy) repetitions of the preceding RE.
            "?"      Matches 0 or 1 (greedy) of the preceding RE.
            *?,+?,?? Non-greedy versions of the previous three special characters.
            {m,n}    Matches from m to n repetitions of the preceding RE.
            {m,n}?   Non-greedy version of the above.
            "\\"     Either escapes special characters or signals a special sequence.
            []       Indicates a set of characters.
                     A "^" as the first character indicates a complementing set.
            "|"      A|B, creates an RE that will match either A or B.
            (...)    Matches the RE inside the parentheses.
                     The contents can be retrieved or matched later in the string.
            (?aiLmsux) The letters set the corresponding flags defined below.
    ......
    
  31. hex(x)

    将整数转换为带前缀 “0x” 前缀的小写十六进制数字符串。

    print(hex(16))
    print(hex(255))
    
    print(f"{255:#x},{255:x}, {255:X}")
    
    # 0x10
    # 0xff
    # 0xff,ff, FF
    
  32. id(object)

    返回对象的“标识值”。该值是一个整数,在此对象的生命周期中保证是唯一且恒定的。两个生命期不重叠的对象可能具有相同的 id()

    a = 1
    b = 1
    print(id(1))
    print(id(a))
    print(id(b))
    # 数字或字符很常用,底层直接有一个表,变量直接指向该表
    # 1883833499888
    # 1883833499888
    # 1883833499888
    c = [12, 3]
    d = [3, 12,90]
    print(id(c))
    print(id(d))
    # 1883838545280
    # 1883838511680
    
  33. input(prompt)

    如果存在 prompt 实参,则将其写入标准输出,末尾不带换行符。接下来,该函数从输入中读取一行,将其转换为字符串(除了末尾的换行符)并返回。

    test = input("请输入牛马\n")
    print(test)
    # 请输入牛马
    # NM
    # NM
    
  34. int(string, /, base=10)

    返回从一个数字或字符串构建的整数对象,或者如果未给出参数则返回 0

    print(int())
    print(int(1.6))
    print(int("123"))
    print(int('   -12_345\n'))
    print(int('FACE', 16))
    print(int('0xface', 0))
    print(int('01110011', base=2))
    
    # 0
    # 1
    # 123
    # -12345
    # 64206
    # 64206
    # 115
    
  35. isinstance(object, classinfo)

    如果 object 参数是 classinfo 参数的实例,或者是其 (直接、间接或 虚拟) 子类的实例则返回 True

    class A():
        pass
    
    class B(A):
        pass
    print(isinstance(B(), A))
    print(isinstance(A(), B))
    print(isinstance(1, int))
    # True
    # False
    # True
    
  36. issubclass(class, classinfo)

    如果 classclassinfo 中的子类(直接、间接或 虚的 ),则返回 True

    class A():
        pass
    
    class B(A):
        pass
    
    print(issubclass(A, (B)))
    print(issubclass(B, (B)))
    print(issubclass(B, (A)))
    
    # False
    # True
    # True
    
  37. iter(object, sentinel)

    返回一个 iterator 对象。 根据是否存在第二个参数,对第一个参数的解读会有很大的不同。 如果没有第二个参数,object 必须是一个支持 iterable 协议 (有 __iter__() 方法) 的多项集对象,或者必须支持序列协议 (有 __getitem__() 方法并使用从 0 开始的整数参数)。 如果它不支持这些协议,则会引发 TypeError。 如果给出了第二个参数 sentinel,则 object 必须是一个可调用对象。 在这种情况下创建的迭代器将针对每次调用其 __next__() 方法不带参数地调用 object;如果返回的值等于 sentinel,则会引发 StopIteration,否则将返回该值。

    my_list = [1, 2, 3, 4, 5]
    iterator = iter(my_list)
    print(next(iterator))  # 1
    print(next(iterator))  # 2
    
  38. len(s)

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

  39. list(iterable)

    虽然被称为函数,list 实际上是一种可变序列类型,强制转换为列表。

    print(list("sssss,d"))
    # ['s', 's', 's', 's', 's', ',', 'd']
    
  40. locals()

    print(locals())
    
    print(locals()){'__name__': '__main__', '__doc__': '\n@FileName:test.py\n@Description:\n@Author:锦沐Python\n@Time:2024/9/10 18:22\n', '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000027DF3524790>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:\\A-XHSPro\\Tk\\Pytest\\test.py', '__cached__': None}
    
    
  41. map(function, iterable, *iterables)

    返回一个将 function 应用于 iterable 的每一项,并产生其结果的迭代器。 如果传入了额外的 iterables 参数,则 function 必须接受相同个数的参数并被用于到从所有可迭代对象中并行获取的项。

    def fun(*args):
        count = 0
        for item in args:
           count += item
        print(count)
    
    print(list(map(fun,[1,2,34,4,], (23,45,6), {1,2,4,8})))
    
    # 32
    # 48
    # 42
    # [None, None, None]
    
  42. max(iterable, ***, default, key=None)

    max(arg1, arg2, *args, key=None)

    返回可迭代对象中最大的元素,或者返回两个及以上实参中最大的。

    如果只提供了一个位置参数,它必须是非空 iterable,返回可迭代对象中最大的元素;如果提供了两个及以上的位置参数,则返回最大的位置参数。

    def lens(x):
        return len(x)
    
    strings = ['apple', 'banana', 'cherry-i']
    print(max(strings, key=lens))  # 'banana'
    
    print(max(12,5,6,7,3))
    empty_list = []
    print(max(empty_list, default=0))  # 0
    
    # cherry-i
    # 12
    # 0
    
  43. class memoryview(object)

    返回由给定实参创建的“内存视图”对象。

    data = bytearray(b'Hello, World!')
    view = memoryview(data)
    
    sliced_view = view[7:12]
    print(sliced_view.tobytes())  # b'World'
    
  44. next(iterator, default)

    通过调用 iterator__next__() 方法获取下一个元素。如果迭代器耗尽,则返回给定的 default

    def fun():
        for i in range(4):
            yield i
    
    f = fun()
    print(next(f, "stop"))
    print(next(f, "stop"))
    print(next(f, "stop"))
    print(next(f, "stop"))
    print(next(f, "stop"))
     
    # 0
    # 1
    # 2
    # 3
    # stop
    
  45. class object

    返回一个不带特征的新对象。object 是所有类的基类。它带有所有 Python 类实例均通用的方法。本函数不接受任何参数。

    class A(object):
    	pass
    
  46. oct(x)

    将整数转换为带前缀 “0o” 的八进制数字符串。

  47. open(file, mode=‘r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
    file:要打开的文件路径,可以是字符串或路径对象。
    mode(可选,默认值为’r’):指定打开文件的模式。常见的模式有:
    ‘r’:只读模式(默认)。
    ‘w’:写入模式,如果文件已存在则截断文件内容,如果文件不存在则创建新文件。
    ‘a’:追加模式,如果文件不存在则创建新文件。
    ‘b’:二进制模式,可以与其他模式结合使用,如’rb’表示以二进制只读模式打开文件。
    ‘t’:文本模式(默认),可以与其他模式结合使用,如’rt’表示以文本只读模式打开文件。
    buffering(可选,默认值为-1):设置缓冲策略。
    为 0 表示无缓冲;为 1 表示行缓冲(仅在文本模式下有效);为大于 1 的整数表示使用指定大小的缓冲区;为 -1(默认值)表示使用系统默认的缓冲策略。
    encoding(可选):指定文件的编码方式,仅在文本模式下有效。例如,‘utf-8’。
    errors(可选):指定编码错误处理方式,仅在文本模式下有效。例如,‘strict’(默认值,遇到编码错误时抛出异常)、‘ignore’(忽略编码错误)等。
    newline(可选):控制换行符的处理方式,仅在文本模式下有效。可以是 None(默认值,使用系统默认的换行符处理方式)、‘’、‘\n’、‘\r’、‘\r\n’ 等。
    closefd(可选,默认值为True):如果为 True(默认值),则文件描述符会在文件关闭时关闭;如果为 False,则文件描述符将保持打开状态,即使文件对象被垃圾回收。仅在以文件描述符作为参数的特殊情况下有用。
    opener(可选):一个可调用对象,用于打开文件。如果指定了 opener,则 open() 函数将使用这个可调用对象而不是默认的 os.open() 函数来打开文件。

    file = open('example.txt', 'w', encoding='utf-8')
    file.write('Hello, world!')
    file.close()
    
    file = open('example.txt', 'a', encoding='utf-8')
    file.write('New entry.\n')
    file.close()
    file = open('example.txt', 'r', encoding='utf-8')
    content = file.read()
    file.close()
    print(content)
    
    file = open('example.txt', 'rb')
    data = file.read()
    file.close()
    print(data)
    
    with open('example.txt', 'r', encoding='utf-8') as file:
        data = file.read()
        print(data)
    
    # Hello, world!New entry.
    # 
    # b'Hello, world!New entry.\r\n'
    # Hello, world!New entry.
    
  48. pow(base, exp, mod=None)

    返回 baseexp 次幂;如果 mod 存在,则返回 baseexp 次幂对 mod 取余(比 pow(base, exp) % mod 更高效)。 两参数形式 pow(base, exp) 等价于乘方运算符: base**exp

    print(pow(2, 3))
    print(pow(2, 3, 3))
    
    # 8
    # 2
    
  49. print(*objects, sep=’ ', end=‘\n’, file=None, flush=False)

    objects 打印输出至 file 指定的文本流,以 sep 分隔并在末尾加上 endsependfileflush 必须以关键字参数的形式给出。

    with open('example.txt', 'a', encoding='utf-8') as file:
    
        print(*["456", "67", 678, 00], sep=" # ", end=" %%\n", file=file)
    
    # 3er # wertfgh %%
    # 456 # 67 %%
    # 456 # 67 # 678 # 0 %%
    
  50. property(fget=None, fset=None, fdel=None, doc=None)

    返回 property 属性。

    class A():
        def __init__(self):
            self.x = 1
    
        def set(self, x):
            self.x = x
    
        def get(self):
            return self.x
    
        def del_x(self):
            del self.x
    
        y = property(get, set, del_x, "property")
    
    
    a = A()
    print(a.y)
    a.y = 12
    print(a.y)
    del a.y
    # print(a.y)
    # 1
    # 12
    # Traceback (most recent call last):
    #   File "D:\A-XHSPro\Tk\Pytest\test.py", line 594, in <module>
    #     print(a.y)
    #   File "D:\A-XHSPro\Tk\Pytest\test.py", line 581, in get
    #     return self.x
    # AttributeError: 'A' object has no attribute 'x'
    
    class B():
        def __init__(self):
            self._x = 1
    
        @property
        def x(self):
            return self._x
    
        @x.setter
        def x(self, x):
            self._x = x
    
        @x.deleter
        def x(self):
            del self._x
    
    b = B()
    print(b.x)
    b.x = 12
    print(b.x)
    del b.x
    print(b.x)
    # 1
    # 12
    # Traceback (most recent call last):
    #   File "D:\A-XHSPro\Tk\Pytest\test.py", line 625, in <module>
    #     print(b.x)
    #   File "D:\A-XHSPro\Tk\Pytest\test.py", line 610, in x
    #     return self._x
    # AttributeError: 'B' object has no attribute '_x'. Did you mean: 'x'?
    
  51. range(start, stop, step=1)

    虽然被称为函数,但 range 实际上是一个不可变的序列类型,

    print(list(range(6)))
    print(list(range(2,6)))
    print(list(range(2,6,2)))
    # [0, 1, 2, 3, 4, 5]
    # [2, 3, 4, 5]
    # [2, 4]
    
  52. repr(object)

    返回包含一个对象的可打印表示形式的字符串。

    class A:
        def __repr__(self):
            return "Class A"
        
    print(repr(A()))
    # Class A
    
  53. reversed(seq)

    返回一个反向的 iteratorseq 必须是一个具有 __reversed__() 方法或是支持序列协议(具有 __len__() 方法和从 0 开始的整数参数的 __getitem__() 方法)的对象

    print(list(reversed([123,435,56,54])))
    # [54, 56, 435, 123]
    
  54. round(number, ndigits=None)

    返回 number 舍入到小数点后 ndigits 位精度的值。 如果 ndigits 被省略或为 None,则返回最接近输入值的整数。

    print(round(12))
    print(round(12.6))
    print(round(12.52345, 2))
    
    # 12
    # 13
    # 12.52
    
  55. set(iterable)

    返回一个新的 set 对象

    set_a = set()
    set_a.add(12)
    set_a.add(2)
    
    set_b = {12,6}
    print(set_a)
    print(set_a | set_b)
    print(set_a & set_b)
    print(set_a - set_b)
    # {2, 12}
    # {2, 12, 6}
    # {12}
    # {2}
    
  56. setattr(object, name, value)

    本函数与 getattr() 相对应。其参数为一个对象、一个字符串和一个任意值。字符串可以为某现有属性的名称,或为新属性。只要对象允许,函数会将值赋给属性。

    class A():
        pass
    
    a = A()
    setattr(a, "name", "Hello")
    print(a.name)
    # Hello
    
  57. slice(start, stop, step=None)

    返回一个表示由 range(start, stop, step) 指定的索引集的 slice 对象。 startstep 参数默认为 None

    my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    print(my_list[slice(2)])
    print(my_list[slice(2, 7)])
    print(my_list[slice(2, 7, 2)])
    
    # [0, 1]
    # [2, 3, 4, 5, 6]
    # [2, 4, 6]
    
  58. sorted(iterable, /, ***, key=None, reverse=False)

    根据 iterable 中的项返回一个新的已排序列表。

    具有两个可选参数,它们都必须指定为关键字参数。

    key 指定带有单个参数的函数,用于从 iterable 的每个元素中提取用于比较的键 (例如 key=str.lower)。 默认值为 None (直接比较元素)。

    my_list = [0, 1, 2, 3,9,5,4,2, 9]
    print(sorted(my_list))
    print(sorted(my_list, reverse=True))
    print(sorted(my_list, key=lambda x: x%3))
    
    # [0, 1, 2, 2, 3, 4, 5, 9, 9]
    # [9, 9, 5, 4, 3, 2, 2, 1, 0]
    # [0, 3, 9, 9, 1, 4, 2, 5, 2]
    
  59. @staticmethod

    将方法转换为静态方法。

    静态方法不会接收隐式的第一个参数。

    class A():
        @staticmethod
        def add(*args):
            result = 0
            for i in args:
                result+=i
            print(result)
    
        def matmul(self, x):
            print(x**2)
    a = A()
    a.add(*[1,2,3,4,5])
    A.add(*[1,2,3,4,5])
    a.matmul(2)
    # 15
    # 15
    # 4
    
  60. str(object=b’', encoding=‘utf-8’, errors=‘strict’)

    返回一个 str 版本的 object

  61. sum(iterable, /, start=0)

    start 开始自左向右对 iterable 的项求和并返回总计值。 iterable 的项通常为数字,而 start 值则不允许为字符串。

    print(sum([2,3,4]))
    print(sum([2,3,4], 1))
    print(sum([12.2,1,1]))
    
    # 9
    # 10
    # 14.2
    
  62. super(type, object_or_type=None)

    返回一个代理对象,它会将方法调用委托给 type 的父类或兄弟类。 这对于访问已在类中被重写的继承方法很有用。

    class A:
        def __init__(self):
            print("Class A")
    
    class B(A):
        def __init__(self):
            super().__init__()
            print("Class B")
    
    class C(A):
        def __init__(self):
            super().__init__()
            print("Class C")
    
    class D(C):
        def __init__(self):
            super().__init__()
            print("Class D")
    
    class E(B, C):
        def __init__(self):
            super().__init__()
            print("Class E")
    C()
    print("___________________")
    B()
    print("___________________")
    D()
    print("___________________")
    E()
    
    # Class A
    # Class C
    # ___________________
    # Class A
    # Class B
    # ___________________
    # Class A
    # Class C
    # Class D
    # ___________________
    # Class A
    # Class C
    # Class B
    # Class E
    
  63. tuple(iterable)

    虽然被称为函数,但 tuple 实际上是一个不可变的序列类型

  64. type(name, bases, dict, **kwds)

    传入一个参数时,返回 object 的类型。 返回值是一个 type 对象,通常与 object.__class__ 所返回的对象相同。

    推荐使用 isinstance() 内置函数来检测对象的类型,因为它会考虑子类的情况。

    x = 5
    print(type(x))  
    
    MyClass = type('MyClass', (), {'attr': 42, 'method': lambda self: print('Hello!')})
    obj = MyClass()
    print(obj.attr)  
    obj.method()  
    
    # <class 'int'>
    # 42
    # Hello!
    
  65. vars(object)

    返回模块、类、实例或任何其它具有 __dict__ 属性的对象的 __dict__ 属性。

    class A:
        def __init__(self):
            self.name = "mi"
    
        def fun(self):
            print("Hello")
    
    print(vars(A()))
    # {'name': 'mi'}
    
  66. zip(*iterables, strict=False)

    在多个迭代器上并行迭代,从每个迭代器返回一个数据项组成元组。

    它会把行变成列,把列变成行。

    for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):
        print(item)
        
    # (1, 'sugar')
    # (2, 'spice')
    # (3, 'everything nice')
    
    for item in zip([1, 2], ['sugar', 'spice', 'everything nice']):
        print(item)
    # (1, 'sugar')
    # (2, 'spice')
    
    for item in zip([1, 2], ['sugar', 'spice', 'everything nice'], strict=True):
        print(item)
    
    # Traceback (most recent call last):
    #   File "D:\A-XHSPro\Tk\Pytest\test.py", line 826, in <module>
    #     for item in zip([1, 2], ['sugar', 'spice', 'everything nice'], strict=True):
    # ValueError: zip() argument 2 is longer than argument 1
    
    print(list(zip(*zip([1, 2], ['sugar', 'spice', 'everything nice']))))
    # [(1, 2), ('sugar', 'spice')]
    
  67. import(name, globals=None, locals=None, fromlist=(), level=0)

    用于动态导入模块。

    一、参数说明

    1. name:要导入的模块名称,可以是一个字符串。例如,'os'表示导入标准库中的os模块。
    2. globals(可选):一个字典,代表当前全局命名空间。如果未提供,则使用当前全局命名空间。
    3. locals(可选):一个字典,代表当前局部命名空间。如果未提供,则使用当前局部命名空间。
    4. fromlist(可选):一个可迭代对象,通常是一个列表,包含要从模块中导入的特定对象名称。如果为空,则只导入模块本身。例如,['path']表示从os模块中导入path对象。
    5. level(可选):指定相对导入的级别。默认值为 0,表示绝对导入。相对导入通常用于在包内部进行导入操作。
    math_module = __import__('math')
    print(math_module.pi)
    
    os_path = __import__('os', fromlist=['path'])
    print(os_path.path.join('dir1', 'dir2'))
    
    # 3.141592653589793
    # dir1\dir2
    

  • 17
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值