Python3,内置函数介绍以及简要代码示例

ε(*・ω・)_/゚:・☆

Python 3.x 中目前共有71个内置函数(不同版本可能略有差异)。按字母顺序排列,并附上简要说明和简单示例:

完整内置函数列表

A

  1. abs(x) - 返回数字的绝对值

    print(abs(-5))  # 输出: 5
    
  2. aiter(async_iterable) - 返回异步迭代器的异步迭代器对象 (Python 3.10+)

  3. all(iterable) - 如果iterable的所有元素都为真(或iterable为空)返回True

    print(all([True, 1, "hello"]))  # True
    print(all([True, 0, "hello"]))  # False
    
  4. anext(async_iterator[, default]) - 从异步迭代器获取下一项 (Python 3.10+)

  5. any(iterable) - 如果iterable的任一元素为真返回True

    print(any([False, 0, "hello"]))  # True
    
  6. ascii(object) - 返回包含对象可打印表示的字符串,非ASCII字符会被转义

    print(ascii("你好"))  # 输出: '\u4f60\u597d'
    

B

  1. bin(x) - 将整数转换为二进制字符串

    print(bin(10))  # 输出: '0b1010'
    
  2. bool([x]) - 返回布尔值,True或False

    print(bool(1))  # True
    print(bool(""))  # False
    
  3. breakpoint(*args, **kws) - 进入调试器 (Python 3.7+)

    # breakpoint()  # 进入pdb调试器
    
  4. bytearray([source[, encoding[, errors]]]) - 返回bytearray对象

    print(bytearray([1, 2, 3]))  # bytearray(b'\x01\x02\x03')
    
  5. bytes([source[, encoding[, errors]]]) - 返回bytes对象

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

C

  1. callable(object) - 检查对象是否可调用

    print(callable(print))  # True
    print(callable(123))    # False
    
  2. chr(i) - 返回Unicode码位为i的字符

    print(chr(65))  # 'A'
    
  3. classmethod(function) - 将函数转换为类方法

  4. compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) - 将源代码编译为代码或AST对象

  5. complex([real[, imag]]) - 创建复数

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

D

  1. delattr(object, name) - 删除对象属性

    class MyClass:
        x = 10
    
    obj = MyClass()
    delattr(obj, 'x')
    
  2. dict(**kwarg) - 创建字典

    print(dict(a=1, b=2))  # {'a': 1, 'b': 2}
    
  3. dir([object]) - 返回对象的属性列表

    print(dir([]))  # 显示列表的方法和属性
    
  4. divmod(a, b) - 返回商和余数的元组

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

E

  1. enumerate(iterable, start=0) - 返回枚举对象

    for i, v in enumerate(['a', 'b']):
        print(i, v)  # 0 a, 1 b
    
  2. eval(expression[, globals[, locals]]) - 执行字符串表达式

    print(eval("3 + 4"))  # 7
    
  3. exec(object[, globals[, locals]]) - 执行动态Python代码

    exec("print('Hello')")  # 输出: Hello
    

F

  1. filter(function, iterable) - 用函数过滤iterable

    print(list(filter(lambda x: x > 0, [-1, 0, 1])))  # [1]
    
  2. float([x]) - 转换为浮点数

    print(float("3.14"))  # 3.14
    
  3. format(value[, format_spec]) - 格式化值

    print(format(123, "05d"))  # '00123'
    
  4. frozenset([iterable]) - 返回不可变集合

    print(frozenset([1, 2, 3]))
    

G

  1. getattr(object, name[, default]) - 获取对象属性

    class MyClass:
        x = 10
    
    print(getattr(MyClass, 'x'))  # 10
    
  2. globals() - 返回当前全局符号表

    print(globals())
    

H

  1. hasattr(object, name) - 检查对象是否有属性

    print(hasattr([], 'append'))  # True
    
  2. hash(object) - 返回对象的哈希值

    print(hash("hello"))
    
  3. help([object]) - 显示帮助信息

    help(print)  # 显示print函数的帮助
    
  4. hex(x) - 将整数转换为十六进制字符串

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

I

  1. id(object) - 返回对象的唯一标识符

    x = []; print(id(x))
    
  2. input([prompt]) - 获取用户输入

    name = input("Your name: ")
    
  3. int([x[, base]]) - 转换为整数

    print(int("10", 2))  # 2 (二进制'10'转为十进制)
    
  4. isinstance(object, classinfo) - 检查对象是否是类的实例

    print(isinstance(10, int))  # True
    
  5. issubclass(class, classinfo) - 检查类是否是另一个类的子类

    print(issubclass(bool, int))  # True
    
  6. iter(object[, sentinel]) - 返回迭代器对象

    i = iter([1, 2]); print(next(i))  # 1
    

L

  1. len(s) - 返回对象的长度

    print(len("hello"))  # 5
    
  2. list([iterable]) - 创建列表

    print(list("abc"))  # ['a', 'b', 'c']
    
  3. locals() - 返回当前局部符号表

    def f():
        x = 10
        print(locals())
    
    f()  # {'x': 10}
    

M

  1. map(function, iterable, …) - 应用函数到iterable的每个元素

    print(list(map(str.upper, ['a', 'b'])))  # ['A', 'B']
    
  2. max(iterable, *[, key, default]) - 返回最大值

    print(max([1, 3, 2]))  # 3
    
  3. memoryview(object) - 返回内存视图对象

    v = memoryview(b'abc')
    print(v[0])  # 97
    
  4. min(iterable, *[, key, default]) - 返回最小值

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

N

  1. next(iterator[, default]) - 从迭代器获取下一项
    i = iter([1, 2])
    print(next(i))  # 1
    

O

  1. object() - 返回新对象实例

    obj = object()
    
  2. oct(x) - 将整数转换为八进制字符串

    print(oct(8))  # '0o10'
    
  3. open(file, mode=‘r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) - 打开文件

    with open('file.txt', 'w') as f:
        f.write('text')
    
  4. ord© - 返回字符的Unicode码位

    print(ord('A'))  # 65
    

P

  1. pow(base, exp[, mod]) - 幂运算

    print(pow(2, 3))  # 8
    
  2. *print(objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False) - 打印输出

    print(1, 2, sep=', ')  # 1, 2
    
  3. property(fget=None, fset=None, fdel=None, doc=None) - 返回属性特性

R

  1. range(stop) - 生成数字序列

    print(list(range(3)))  # [0, 1, 2]
    
  2. repr(object) - 返回对象的可打印表示

    print(repr("hello"))  # "'hello'"
    
  3. reversed(seq) - 返回反向迭代器

    print(list(reversed([1, 2, 3])))  # [3, 2, 1]
    
  4. round(number[, ndigits]) - 四舍五入

    print(round(3.14159, 2))  # 3.14
    

S

  1. set([iterable]) - 创建集合

    print(set([1, 2, 2, 3]))  # {1, 2, 3}
    
  2. setattr(object, name, value) - 设置对象属性

    class MyClass: pass
    obj = MyClass()
    setattr(obj, 'x', 10)
    
  3. slice(stop) - 返回切片对象

    s = slice(1, 5, 2)
    print([0,1,2,3,4,5][s])  # [1, 3]
    
  4. sorted(iterable, *, key=None, reverse=False) - 返回排序后的列表

    print(sorted([3, 1, 2]))  # [1, 2, 3]
    
  5. staticmethod(function) - 将函数转换为静态方法

  6. str(object=’’) - 转换为字符串

    print(str(123))  # '123'
    
  7. sum(iterable, /, start=0) - 求和

    print(sum([1, 2, 3]))  # 6
    
  8. super([type[, object-or-type]]) - 返回代理对象以调用父类方法

T

  1. tuple([iterable]) - 创建元组

    print(tuple("abc"))  # ('a', 'b', 'c')
    
  2. type(object) - 返回对象类型

    print(type(10))  # 
    
  3. type(name, bases, dict, **kwds) - 创建新类型

V

  1. vars([object]) - 返回对象的__dict__属性
    class MyClass:
        def __init__(self):
            self.x = 10
    
    print(vars(MyClass()))
    

Z

  1. zip(*iterables, strict=False) - 并行迭代多个iterable
    print(list(zip([1, 2], ['a', 'b'])))  # [(1, 'a'), (2, 'b')]
    

特殊内置函数

还有一些特殊的内置函数和常量:

  • __import__(name, globals=None, locals=None, fromlist=(), level=0) - 导入模块的内部实现
  • Ellipsis... - 省略号对象
  • NotImplemented - 特殊值,表示操作未实现
  • True, False - 布尔值
  • None - 空值

要查看当前Python版本中的所有内置函数,可以在交互式解释器中运行:

import builtins
print(dir(builtins))

你可能感兴趣的:(Python3,内置函数介绍以及简要代码示例)