• Python内置方法/函数


     

    abs()

    返回数字的绝对值。

    abs(x)
    

      

    all()

    用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False。

    元素除了是 0、空、None、False 外都算 True。

    all(iterable) #iterable -- 元组或列表
    >>> all([1,2,0])
    False
    >>> all([1,2,1])
    True
    

    any()  

    用于判断给定的可迭代参数 iterable 是否全部为 False,则返回 False,如果有一个为 True,则返回 True。

    元素除了是 0、空、FALSE 外都算 TRUE。

    >>> any([1,2,0])
    True
    >>> any([0,0])
    False
    

      

    ascii()

    中文转ASC码。

    >>> ascii([1,2,"测试"])
    "[1, 2, '\u6d4b\u8bd5']"
    

      

    bin()

    十进制转二进制。

    bin(x)
    

      

    bool()

    判断真假。

    >>> bool(1)
    True
    >>> bool(0)
    False
    

      

    bytes()

    返回一个新的“bytes”对象, 是一个不可变序列。

    class bytes([source[, encoding[, errors]]])
    >>> bytes('abcd',encoding="utf-8")
    b'abcd'
    

      

    bytearray()

    返回一个新的 bytes 数组。 bytearray 类是一个可变序列。改二进制字符。

    bytearray([source[, encoding[, errors]]])
    
    >>> a = bytearray('abcd',encoding="utf-8")
    >>> a[0]
    97
    >>> a[0] = 99
    >>> a
    bytearray(b'cbcd')
    

      

    callable()

    如果参数 object 是可调用的就返回 True,否则返回 False。

    >>> callable(int)
    True
    

      

    chr()

    chr() 用一个范围在 range(256)内的(就是0~255)整数作参数,返回一个对应的字符。

    >>> chr(100)
    'd'
    

      

    ord()

    ord() 函数是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值。

    >>> ord('a')
    97
    

     

    @classmethod

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

    class C:
        @classmethod
        def f(cls, arg1, arg2, ...): ...
    

      

    compile()

    compile() 函数将一个字符串编译为字节代码,用于底层编译的。

    语法:

    compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
    
    将 source 编译成代码或 AST 对象。代码对象可以被 exec() 或 eval() 执行。source 可以是常规的字符串、字节字符串,或者 AST 对象。
    filename 实参需要是代码读取的文件名
    mode 实参指定了编译代码必须用的模式。如果 source 是语句序列,可以是 'exec';如果是单一表达式,可以是 'eval';如果是单个交互式语句,可以是 'single'。
    

      

    >>> code = "for i in range(10):print(i)"
    >>> c = compile(code,'','exec')
    >>> c
    <code object <module> at 0x000001A23F969300, file "", line 1>
    >>> exec(c)
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    

      

    也可以是表达式。

    >>> code = "1+2+3/2"
    >>> c = compile(code,'','eval')
    >>> eval(c)
    4.5
    

      

    exec()

    exec(object[, globals[, locals]])

    这个函数支持动态执行 Python 代码。object 必须是字符串或者代码对象。如果是字符串,那么该字符串将被解析为一系列 Python 语句并执行(除非发生语法错误)。 如果是代码对象,它将被直接执行。在任何情况下,被执行的代码都需要和文件输入一样是有效的

    complex()

    返回值为 real + imag*1j 的复数,或将字符串或数字转换为复数。

    >>> complex(1,2)
    (1+2j)
    

      

    delattr()

    delattr(object, name)
    

    实参是一个对象和一个字符串。该字符串必须是对象的某个属性。如果对象允许,该函数将删除指定的属性。

    例如 delattr(x, 'foobar') 等价于 del x.foobar 。

    dir()

    dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。

    >>> dir(code)
    ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
    

      

    divmod()

    它将两个(非复数)数字作为实参,并在执行整数除法时返回一对商和余数。

    >>> divmod(10,2)
    (5, 0)
    

      

    enumerate

    enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

    >>> a=['a','b','b','d','e']
    >>> for i,e in enumerate(a):
    ...     print(i,e)
    ...
    0 a
    1 b
    2 b
    3 d
    4 e
    

      

    eval()

    eval() 函数用来执行一个字符串表达式,并返回表达式的值。

    可以把字符串变成字典。

    >>> a="{'a':'b'}"
    >>> type(a)
    <class 'str'>
    >>> b = eval(a)
    >>> type(b)
    <class 'dict'>
    

      

    filter()

    filter(function, iterable)

    用 iterable 中函数 function 返回真的那些元素,构建一个新的迭代器。iterable 可以是一个序列,一个支持迭代的容器,或一个迭代器。

    >>> f = filter(lambda n:n>5,range(10))
    >>> f
    <filter object at 0x000001A23FA31BE0>
    >>> for i in f:
    ...     print(i)
    ...
    6
    7
    8
    9
    

      

    map()

    返回一个将 function 应用于 iterable 中每一项并输出其结果的迭代器。

    map(function, iterable)
    

      

    >>> m = map(lambda n:n*n,range(10))
    >>> for i in m:
    ...     print(i)
    ...
    0
    1
    4
    9
    16
    25
    36
    49
    64
    81
    

      

    float()

    返回从数字或字符串 x 生成的浮点数。

    >>> float(2)
    2.0
    

      

    format()

    将 value 转换为 format_spec 控制的“格式化”表示。

    >>> "{}".format("hello")
    'hello'
    

      

    frozenset()

    frozenset([iterable])
    

      

    frozenset() 返回一个冻结的集合,冻结后集合不能再添加或删除任何元素。

    >>> l = [1,2,3,4]
    >>> dir(l)
    ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
    >>> frozenset(l)
    frozenset({1, 2, 3, 4})
    >>> x = frozenset(l)
    >>> dir(x)
    ['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'copy', 'difference', 'intersection', 'isdisjoint', 'issubset', 'issuperset', 'symmetric_difference', 'union']
    

      

    getattr()

    getattr(object, name[, default])

    返回对象命名属性的值。name 必须是字符串。如果该字符串是对象的属性之一,则返回该属性的值。例如, getattr(x, 'foobar') 等同于 x.foobar。

    globals()

    以键值对的方式返回当前程序的所有变量。

    >>> print(globals())
    {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': "{'a':'b'}", 'code': '1+2+3/2', 'c': <code object <module> at 0x000001A23F9699C0, file "", line 1>, 'i': 81, 'e': 'e', 'b': {'a': 'b'}, 'f': <filter object at 0x000001A23FA31BE0>, 'm': <map object at 0x000001A23FA31C18>, 'l': [1, 2, 3, 4], 'x': frozenset({1, 2, 3, 4})}
    

      

    hash()

    返回该对象的哈希值(如果它有的话)。哈希值是整数。

    >>> hash('abcs')
    -5430407018906191666
    

      

    help()

    查看函数或模块用途的详细说明。

    >>> help(chr)
    Help on built-in function chr in module builtins:
    
    chr(i, /)
        Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
    

      

    hex()

    将一个指定数字转换为 16 进制数。

    >>> hex(15)
    '0xf'
    

      

    id()

    获取对象的内存地址。

    >>> a="hello"
    >>> id(a)
    2047968913928
    

      

    int()

    将一个字符串或数字转换为整型。

    >>> int("111")
    111
    

      

    input()

    接受一个标准输入数据,返回为 string 类型。

    >>> str = input("Input value")
    Input value hello
    >>> str
    ' hello'
    

      

    isinstance()

    判断一个对象是否是一个已知的类型。

    >>>a = 2
    >>> isinstance (a,int)
    True
    >>> isinstance (a,str)
    False
    

      

    issubclass()

    判断参数 class 是否是类型参数 classinfo 的子类。

    class A:
        pass
    class B(A):
        pass
        
    print(issubclass(B,A))    # 返回 True
    

      

    iter()

    用来生成迭代器。

    iter(object[, sentinel])
    • object -- 支持迭代的集合对象。
    • sentinel -- 如果传递了第二个参数,则参数 object 必须是一个可调用的对象(如,函数),此时,iter 创建了一个迭代器对象,每次调用这个迭代器对象的__next__()方法时,都会调用 object。

      

    >>>lst = [1, 2, 3]
    >>> for i in iter(lst):
    ...     print(i)
    ... 
    1
    2
    3
    

      

    len()

    返回对象(字符、列表、元组等)长度或项目个数。

    >>> len('avc')
    3
    

      

    locals()

    以字典类型返回当前位置的全部局部变量。

    >>> def a(): 
    ...     x='aaa' 
    ...     print(locals())
    ...
    >>> a()
    {'x': 'aaa'}
    

      

    list()

    用于将元组或字符串转换为列表。

    >>> a = '[1,2,3,4]'
    >>> x = list(a)
    >>> x
    ['[', '1', ',', '2', ',', '3', ',', '4', ']']
    

      

    max()

    返回给定参数的最大值,参数可以为序列。

    >>> max(100,1000,10)
    1000
    

      

    min()

    返回给定参数的最小值,参数可以为序列。

    >>> min('a','b','c')
    'a'
    

      

    memoryview()

    返回给定参数的内存查看对象(Momory view)。

    >>>v = memoryview(bytearray("abcefg", 'utf-8'))
    >>> print(v[1])
    98
    >>> print(v[-1])
    103
    >>> print(v[1:4])
    <memory at 0x10f543a08>
    >>> print(v[1:4].tobytes())
    b'bce'
    >>>
    

      

    next()

    返回迭代器的下一个项目,相当于__next__()。

    it = iter([1, 2, 3, 4, 5])
    while True:
        try:
            x = next(it)
            print(x)
        except StopIteration:
            break
    

      

    object()

    面向对象中的对象。

    oct()

    将一个整数转换成8进制字符串

    >>> oct(1)
    '0o1'
    

      

    open()

    用于打开一个文件,并返回文件对象。

    open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

    • file: 必需,文件路径(相对或者绝对路径)。
    • mode: 可选,文件打开模式
    • buffering: 设置缓冲
    • encoding: 一般使用utf8
    • errors: 报错级别
    • newline: 区分换行符
    • closefd: 传入的file参数类型
    • opener:

      

    pow()

    返回x的y次方的值。

    >>> import math
    >>> math.pow(2,3)
    8.0
    

      

    print()

    用于打印输出。

    print(*objects, sep=' ', end='
    ', file=sys.stdout, flush=False)
    • objects -- 复数,表示可以一次输出多个对象。输出多个对象时,需要用 , 分隔。
    • sep -- 用来间隔多个对象,默认值是一个空格。
    • end -- 用来设定以什么结尾。默认值是换行符 ,我们可以换成其他字符串。
    • file -- 要写入的文件对象。
    • flush -- 输出是否被缓存通常决定于 file,但如果 flush 关键字参数为 True,流会被强制刷新。

      

    property()

    新式类中返回属性值。

    class property([fget[, fset[, fdel[, doc]]]])
    参数
    fget -- 获取属性值的函数
    fset -- 设置属性值的函数
    fdel -- 删除属性值函数
    doc -- 属性描述信息
    

      

    class C(object):
        def __init__(self):
            self._x = None
     
        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.")
    

      

    range()

    返回的是一个可迭代对象(类型是对象)。

    >>>range(5)
    range(0, 5)
    

      

    repr()

    将对象转化为供解释器读取的形式。

    >>> a
    '[1,2,3,4]'
    >>> repr(a)
    "'[1,2,3,4]'"
    

      

    reversed()

    返回一个反转的迭代器。

    >>> a="admin"
    >>> reversed(a)
    <reversed object at 0x000001DCD474A6A0>
    >>> print(a)
    admin

    round()

    返回浮点数 x 的四舍五入值。

    round( x [, n]  )
    >>> round(1.335,2)
    1.33
    

      

    set()

    创建一个无序不重复元素集。

    >>> x=set('test')
    >>> x
    {'t', 'e', 's'}
    

     

    slice()

    实现切片对象,主要用在切片操作函数里的参数传递。

    setattr(object, name, value)
    • object -- 对象。
    • name -- 字符串,对象属性。
    • value -- 属性值。

    >>> a = range(0,20) >>> a[slice(5,10)] range(5, 10)

      

     

    setattr()

    对应函数 getattr(),用于设置属性值,该属性不一定是存在的。

    setattr(object, name, value)
      object -- 对象。
      name -- 字符串,对象属性。
      value -- 属性值。
    
    >>>class A(object):
    ...     bar = 1
    ... 
    >>> a = A()
    >>> getattr(a, 'bar')          # 获取属性 bar 值
    1
    >>> setattr(a, 'bar', 5)       # 设置属性 bar 值
    >>> a.bar
    5
    

      

    sorted()

    对所有可迭代的对象进行排序操作。

    >>> a = [1,3,5,97,12,55,33]
    >>> x = sorted(a)
    >>> x
    [1, 3, 5, 12, 33, 55, 97]
    

      

    staticmethod()

    返回函数的静态方法。

    class C(object):
        @staticmethod
        def f():
            print('runoob');
     
    C.f();          # 静态方法无需实例化
    cobj = C()
    cobj.f()        # 也可以实例化后调用
    
    ##输出
    runoob
    runoob

    str()

    将对象转化为文本的形式。

    sum()

    对系列进行求和计算。

    sum(iterable[, start])
    • iterable -- 可迭代对象,如:列表、元组、集合。
    • start -- 指定相加的参数,如果没有设置这个值,默认为0。
    >>> a = [1,2,3]
    >>> sum(a)
    6
    

      

    super()

    用于调用父类(超类)的一个方法。用于面向对象继承。

    super(type[, object-or-type])
    • type -- 类。
    • object-or-type -- 类,一般是 self

      

    tuple()

    将可迭代系列(如列表)转换为元组。

    tuple( iterable )
    iterable -- 要转换为元组的可迭代序列。

      

    type()

    只有第一个参数则返回对象的类型,三个参数返回新的类型对象。

    type(object)
    type(name, bases, dict)
    • name -- 类的名称。
    • bases -- 基类的元组。
    • dict -- 字典,类内定义的命名空间变量。

      

    vars()

    返回对象object的属性和属性值的字典对象。

    >>> class Test:
    ...     a = 1
    ... 
    >>> print(vars(Test))
    {'a': 1, '__module__': '__main__', '__doc__': None}
    

      

    zip()

    用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。

    >>> a
    [1, 2, 3]
    >>> b=['a','b','c']
    >>> print(zip(a,b))
    <zip object at 0x000001DCD4A30108>
    >>> for i in zip(a,b):
    ...     print(i)
    ...
    (1, 'a')
    (2, 'b')
    (3, 'c')
    

      

    __import__()

    用于动态加载类和函数 。

    __import__('a')        # 导入 a.py 模块
    

      

  • 相关阅读:
    不得不爱开源 Wijmo jQuery 插件集(6)【Popup】(附页面展示和源码)
    遗漏的知识点
    初识函数
    ==和is的区别 以及编码和解码
    函数的动态参数 及函数嵌套
    基本数据类型补充、set集合、深浅拷贝
    文件操作
    基本数据类型之“字典”
    建立自己的Servlet
    还原误删数据笔记
  • 原文地址:https://www.cnblogs.com/endust/p/12299375.html
Copyright © 2020-2023  润新知