zoukankan      html  css  js  c++  java
  • Python内置函数大全

    Python内置函数大全

    数学运算相关

     

    abs(x) 求绝对值 1、参数可以是整型,也可以是复数 2、若参数是复数,则返回复数的模
    complex([real[, imag]]) 创建一个复数
    divmod(a, b) 分别取商和余数 注意:整型、浮点型都可以
    float([x]) 将一个字符串或数转换为浮点数。如果无参数将返回0.0
    int([x[, base]]) 将一个字符转换为int类型,base表示进制
    long([x[, base]]) 将一个字符转换为long类型(Python3已移除)
    pow(x, y[, z]) 返回x的y次幂
    range([start], stop[, step]) 产生一个序列,默认从0开始
    round(x[, n]) 四舍五入
    sum(iterable[, start]) 对集合求和
    oct(x) 将一个数字转化为8进制
    hex(x) 将整数x转换为16进制字符串
    chr(i) 返回整数i对应的ASCII字符
    bin(x) 将整数x转换为二进制字符串
    bool([x]) 将x转换为Boolean类型
    # ==== abs ==== 绝对值
    print(abs(1))  # 1
    print(abs(-1))  # 1
    # ==== complex ==== 复数
    print(complex())  # 0j
    # ==== divmod ==== Ps:分页时会使用
    print(divmod(10, 3))  # (3, 1)
    # ==== float ====
    # 省略
    # ==== int ====
    # 省略
    # ==== long ====
    # Python3已移除
    # ==== pow ====
    print(pow(10, 2, 5))  # 0
    print(10 ** 2 % 5)  # 0
    # ==== range ====
    # 省略
    # ==== round ==== 四舍五入
    round(3.3)
    ​
    # ==== sum ==== 
    # 省略
    # ==== oct ==== 
    # 省略
    # ==== hex ====
    # 省略
    # ==== chr ====
    # 省略
    # ==== bin ====
    # 省略
    # ==== bool ====
    # 省略
    操作演示

    操作相关

    basestring() str和unicode的超类 不能直接调用,可以用作isinstance判断。Python3已移除
    format(value [, format_spec]) 格式化输出字符串 格式化的参数顺序从0开始,如“I am {0},I like {1}”
    unichr(i) 返回给定int类型的unicode,Python3已移除。
    enumerate(sequence [, start = 0]) 返回一个可枚举的对象,该对象的next()方法将返回一个tuple
    iter(o[, sentinel]) 生成一个对象的迭代器,第二个参数表示分隔符
    max(iterable, args...) 返回集合中的最大值
    min(iterable, args...) 返回集合中的最小值
    dict([arg]) 创建数据字典
    list([iterable]) 将一个集合类转换为另外一个集合类
    set() set对象实例化
    frozenset([iterable]) 产生一个不可变的set
    str([object]) 转换为string类型
    sorted(iterable[, cmp[, key[, reverse]]]) 对集合排序
    tuple([iterable]) 生成一个tuple类型
    xrange([start], stop[, step]) xrange()函数与range()类似,但xrnage()并不创建列表,而是返回一个xrange对象,它的行为与列表相似,但是只在需要时才计算列表值,当列表很大时,这个特性能为我们节省内存。Python3已移除。
    # ==== basestring ====
    # Python3已移除
    # ==== format ====
    # 省略
    # ==== unichr ====
    # Python3已移除
    # ==== enumerate ==== 枚举
    # 省略
    # ==== iter ====
    # 省略
    # ==== max ====
    # 省略
    # ==== min ====
    # 省略
    # ==== dict ====
    # 省略
    # ==== list ====
    # 省略
    # ==== set ====
    # 省略
    # ==== srozenset ==== 创建不可变集合
    # 在基本数据类型中写过,故省略
    # ==== tuple ====
    # 省略
    # ==== xrange ====
    # 同range,Python3已移除
    操作演示

     

    逻辑判断相关

    all(iterable) 1、集合中的元素都为真的时候为真 2、特别的,若为空串返回为True
    any(iterable) 1、集合中的元素有一个为真的时候为真 2、特别的,若为空串返回为False
    cmp(x, y) 如果x < y ,返回负数;x == y, 返回0;x > y,返回正数Python3已移除。
    # ==== all ====
    print(all([1,2,3])) # True
    print(all([(),{},[],None,0])) # False
    print(all([])) # True
    # ==== any ==== 
    print(any([1,None,0])) # True 
    print(any([(),{},[],None,0])) # False
    print(any([])) # False
     
    # ==== cmp ====
    # Python3已移除
    操作演示

     

    反射相关

    callable(object) 检查对象object是否可调用 1、类是可以被调用的 2、实例是不可以被调用的,除非类中声明了call方法
    classmethod() 1、注解,用来说明这个方式是个类方法 2、类方法即可被类调用,也可以被实例调用 3、类方法类似于Java中的static方法 4、类方法中不需要有self参数
    compile(source, filename,mode[, flags[, dont_inherit]]) 将source编译为代码或者AST对象。代码对象能够通过exec语句来执行或者eval()进行求值。 1、参数source:字符串或者AST(Abstract Syntax Trees)对象。 2、参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。 3、参数model:指定编译代码的种类。可以指定为 ‘exec’,’eval’,’single’。 4、参数flag和dont_inherit:这两个参数暂不介绍Python3已移除
    dir([object]) 1、不带参数时,返回当前范围内的变量、方法和定义的类型列表; 2、带参数时,返回参数的属性、方法列表。 3、如果参数包含方法dir(),该方法将被调用。当参数为实例时。 4、如果参数不包含dir(),该方法将最大限度地收集参数信息
    delattr(object, name) 删除object对象名为name的属性
    eval(expression [, globals [, locals]]) 计算表达式expression的值
    execfile(filename [, globals [, locals]]) 用法类似exec(),不同的是execfile的参数filename为文件名,而exec的参数为字符串。Python3已移除
    filter(function, iterable) 构造一个序列,等价于[ item for item in iterable if function(item)] 1、参数function:返回值为True或False的函数,可以为None 2、参数iterable:序列或可迭代对象
    getattr(object, name [, defalut]) 获取一个类的属性
    globals() 返回一个描述当前全局符号表的字典
    hasattr(object, name) 判断对象object是否包含名为name的特性
    hash(object) 如果对象object为哈希表类型,返回对象object的哈希值
    id(object) 返回对象的唯一标识
    isinstance(object, classinfo) 判断object是否是class的实例
    issubclass(class, classinfo) 判断是否是子类
    len(s) 返回集合长度
    locals() 返回当前的变量字典
    map(function, iterable, ...) 遍历每个元素,执行function操作
    memoryview(obj) 返回一个内存镜像类型的对象
    next(iterator[, default]) 类似于iterator.next()
    object() 基类
    property([fget[, fset[, fdel[, doc]]]]) 属性访问的包装类,设置后可以通过c.x=value等来访问setter和getter
    reduce(function, iterable[, initializer]) 合并操作,从第一个开始是前两个参数,然后是前两个的结果与第三个合并进行处理,以此类推Python3以将该函数移除至移除内置函数
    reload(module) 重新加载模块Python3已移除。
    setattr(object, name, value) 设置属性值
    repr(object) 将一个对象变幻为可打印的格式
    slice() 切片
    staticmethod 声明静态方法,类似于类的工具包
    super(type[, object-or-type]) 根据mro继承关系列表调用父类方法
    type(object) 返回该object的类型
    vars([object]) 返回对象的变量,若无参数与dict()方法类似
    bytearray([source [, encoding [, errors]]]) 返回一个byte数组 1、如果source为整数,则返回一个长度为source的初始化数组; 2、如果source为字符串,则按照指定的encoding将字符串转换为字节序列; 3、如果source为可迭代类型,则元素必须为[0 ,255]中的整数; 4、如果source为与buffer接口一致的对象,则此对象也可以被用于初始化bytearray.
    zip([iterable, ...]) 拉链函数,将两个可迭代对象进行一一组合。多余的部分舍弃
    class Test(object):
        pass
    ​
    ​
    t1 = Test()
    ​
    # ==== callable ==== # 判断对象是否可被调用,即调用元类的__call__。(注意:通俗意义上的实例对象不能拿到元类的__call__,而类对象则可以)
    print(callable(Test))  # True
    print(callable(t1))  # False
    # ==== classmethod ====
    # 省略
    # ==== complie ====
    # Python3已移除
    # ==== dir ==== # 相当于查看能被 . 出来的属性和方法
    print(dir(t1))
    print(dir(Test))
    ​
    # ==== delattr ====
    # 省略,这个是调用内部的 __delattr__ 来对实例字典进行操作。
    # ==== eval ====
    # 省略
    # ==== execfile ====
    # Python3已移除
    # ==== filter ====
    # 省略
    # ==== getattr ====
    # 省略,这个是调用内部的 __getattribute__ 来进行操作。有则进行
    # 返回,无则抛出异常,可设定默认返回值。将在获取失败时触发。
    # ==== globals ====
    print(globals()) # 返回全局字典
    # ==== hasattr ==== 判断对象是否具有某个属性或方法。也是调用内部的__getattribute__进行操作,若属性查找没有则捕获异常返回False。
    print(hasattr(t1, "__dict__"))  # True
    print(hasattr(t1, "__getitem__"))  # False
    print(hasattr(Test, "__dict__"))  # True
    print(hasattr(Test, "__getitem__"))  # False
    # ==== id ====
    # 省略
    # ==== isinstance ==== 判断object是否是class的实例
    print(isinstance(1,int)) # True
    print(isinstance(1,bool)) # False
    # ==== issubclass ===== 判断是否是子类
    print(issubclass(Test,object)) # True
    # ==== len ====
    # 省略
    # ==== locals ====  返回当前的变量列表
    print(locals())
    ​
    # ==== map ====
    # 省略
    # ==== memoryview ====
    # 没用过
    # ==== next ====
    # 省略
    # ==== object ====
    # 所有类的基类
    print(object) # <class 'object'>
    # ==== property ====
    # 省略
    # ==== reduce ====
    # Python3以将该函数移除至移除内置函数
    # ==== reload ====
    # Python3已移除
    # ==== setattr ====
    # 省略,这个是调用内部的 __setattr__ 来进行操作。
    # ==== reper ====
    # 省略,这个是调用内部的 __reper__ 来进行操作。常用于交互式环境
    # ==== slice ==== 切片
    li = [1,2,3,4,5,6]
    print(li[0:-1:2]) # [1, 3, 5]
    i = slice(0,-1,2)
    print(li[i]) # [1, 3, 5]
    # ==== staticmethod ====
    # 省略
    # ==== super ====
    # 省略
    # ==== type ====
    # 省略
    # ==== vars ==== # 相当于 返回对象的__dict__ ,好像是调用的 __slots__ ,具体作用在类的双下方法中会进行介绍
    print(vars(t1)) # {}
    t1.name = "new"
    print(vars(t1)) # {'name': 'new'}
    # ==== bytearray ====
    # 冷门方法,八百年没用过一次。不介绍
    # ==== zip ====  重要方法!拉链函数,将两个可迭代对象进行一一组合。多余的部分舍弃
    l1 = [1,2,3,4]
    l2 = ("A","B","C")
    ​
    print(list(zip(l1,l2))) # [(1, 'A'), (2, 'B'), (3, 'C')]
    操作演示

     

    IO操作相关

    file(filename [, mode [, bufsize]]) file类型的构造函数,作用为打开一个文件,如果文件不存在且mode为写或追加时,文件将被创建。添加‘b’到mode参数中,将对文件以二进制形式操作。添加‘+’到mode参数中,将允许对文件同时进行读写操作 1、参数filename:文件名称。 2、参数mode:'r'(读)、'w'(写)、'a'(追加)。 3、参数bufsize:如果为0表示不进行缓冲,如果为1表示进行行缓冲,如果是一个大于1的数表示缓冲区的大小 。Python3已移除
    input([prompt]) 获取用户输入 推荐使用raw_input,因为该函数将不会捕获用户的错误输入
    open(name[, mode[, buffering]]) 打开文件 与file有什么不同?推荐使用open
    print 打印函数。
    raw_input([prompt]) 设置输入,输入都是作为字符串处理。Python3已移除
    # === file ====
    # Python3已移除
    # ==== input ====
    # 省略
    # ==== open ====
    # 省略
    # ==== print ====
    # 省略
    # ==== raw_input ====
    # Python3已移除
     
    操作演示

    其他

    help() 帮助信息
    print(help(list))
    ​
    """
    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:
     |  
     |  __add__(self, value, /)
     |      Return self+value.
     |  
     |  __contains__(self, key, /)
     |      Return key in self.
     |  
     |  __delitem__(self, key, /)
     |      Delete self[key].
     |  
     |  __eq__(self, value, /)
     |      Return self==value.
     |  
     |  __ge__(self, value, /)
     |      Return self>=value.
     |  
     |  __getattribute__(self, name, /)
     |      Return getattr(self, name).
     |  
     |  __getitem__(...)
     |      x.__getitem__(y) <==> x[y]
     |  
     |  __gt__(self, value, /)
     |      Return self>value.
     |  
     |  __iadd__(self, value, /)
     |      Implement self+=value.
     |  
     |  __imul__(self, value, /)
     |      Implement self*=value.
     |  
     |  __init__(self, /, *args, **kwargs)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |  
     |  __iter__(self, /)
     |      Implement iter(self).
     |  
     |  __le__(self, value, /)
     |      Return self<=value.
     |  
     |  __len__(self, /)
     |      Return len(self).
     |  
     |  __lt__(self, value, /)
     |      Return self<value.
     |  
     |  __mul__(self, value, /)
     |      Return self*value.
     |  
     |  __ne__(self, value, /)
     |      Return self!=value.
     |  
     |  __repr__(self, /)
     |      Return repr(self).
     |  
     |  __reversed__(self, /)
     |      Return a reverse iterator over the list.
     |  
     |  __rmul__(self, value, /)
     |      Return value*self.
     |  
     |  __setitem__(self, key, value, /)
     |      Set self[key] to value.
     |  
     |  __sizeof__(self, /)
     |      Return the size of the list in memory, in bytes.
     |  
     |  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.
     |  
     |  count(self, value, /)
     |      Return number of occurrences of value.
     |  
     |  extend(self, iterable, /)
     |      Extend list by appending elements from the iterable.
     |  
     |  index(self, value, start=0, stop=9223372036854775807, /)
     |      Return first index of value.
     |      
     |      Raises ValueError if the value is not present.
     |  
     |  insert(self, index, object, /)
     |      Insert object before index.
     |  
     |  pop(self, index=-1, /)
     |      Remove and return item at index (default last).
     |      
     |      Raises IndexError if list is empty or index is out of range.
     |  
     |  remove(self, value, /)
     |      Remove first occurrence of value.
     |      
     |      Raises ValueError if the value is not present.
     |  
     |  reverse(self, /)
     |      Reverse *IN PLACE*.
     |  
     |  sort(self, /, *, key=None, reverse=False)
     |      Sort the list in ascending order and return None.
     |      
     |      The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
     |      order of two equal elements is maintained).
     |      
     |      If a key function is given, apply it once to each list item and sort them,
     |      ascending or descending, according to their function values.
     |      
     |      The reverse flag can be set to sort in descending order.
     |  
     |  ----------------------------------------------------------------------
     |  Static methods defined here:
     |  
     |  __new__(*args, **kwargs) from builtins.type
     |      Create and return a new object.  See help(type) for accurate signature.
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  __hash__ = None
    ​
    None
    """
    操作演示
  • 相关阅读:
    Eclipse下配置javaweb项目快速部署到tomcat
    SpringMVC中如何在网站启动、结束时执行代码(详细,确保可用)
    # 浏览器兼容性 小结
    # HTML && CSS 学习笔记
    # li鼠标移入移出,点击,变背景色,变checkbox选中状态
    SpringMVC开发入门讲义
    Spring同mybatis整合讲义(事物)
    Spring中的AOP开发
    Spring框架IOC,DI概念理解
    Mybatis里SQL语句的分页
  • 原文地址:https://www.cnblogs.com/Yunya-Cnblogs/p/13092445.html
Copyright © 2011-2022 走看看