美文网首页Python内置函数
Python内置函数(4)

Python内置函数(4)

作者: 复苏的兵马俑 | 来源:发表于2020-02-18 12:24 被阅读0次

    Python内置函数(1)— abs()、all()、any()、ascii()、bin()、bool()、breakpoint()、bytearray()、bytes()、callable()。
    Python内置函数(2)— chr()、classmethod()、compile()、complex()、delattr()、dict()、dir()、divmod()、enumerate()、eval()。
    Python内置函数(3)— exec()、filter()、float()、format()、frozenset()、getattr()、globals()、hasattr()、hash()、help()。
    Python内置函数(4)— hex()、id()、input()、int()、isinstance()、issubclass、iter()、len()、list()、locals()。
    Python内置函数(5)— map()、max()、memoryview()、min()、next()、object()、oct()、open()、ord()、pow()。
    Python内置函数(6)— print()、property()、range()、repr()、reversed()、round()、set()、setattr()、slice()、sorted()。
    Python内置函数(7)— staticmethod()、str()、sum()、super()、tuple()、type()、vars()、zip()、__import__()。

    内置函数(原文)
    abs() delattr() hash() memoryview() set()
    all() dict() help() min() setattr()
    any() dir() hex() next() slice()
    ascii() divmod() id() object() sorted()
    bin() enumerate() input() oct() staticmethod()
    bool() eval() int() open() str()
    breakpoint() exec() isinstance() ord() sum()
    bytearray() filter() issubclass() pow() super()
    bytes() float() iter() print() tuple()
    callable() format() len() property() type()
    chr() frozenset() list() range() vars()
    classmethod() getattr() locals() repr() zip()
    compile() globals() map() reversed() __import__()
    complex() hasattr() max() round()
    内置函数(中文)
    abs() delattr() hash() memoryview() set()
    all() dict() help() min() setattr()
    any() dir() hex() next() slice()
    ascii() divmod() id() object() sorted()
    bin() enumerate() input() oct() staticmethod()
    bool() eval() int() open() str()
    breakpoint() exec() isinstance() ord() sum()
    bytearray() filter() issubclass() pow() super()
    bytes() float() iter() print() tuple()
    callable() format() len() property() type()
    chr() frozenset() list() range() vars()
    classmethod() getattr() locals() repr() zip()
    compile() globals() map() reversed() __import__()
    complex() hasattr() max() round()
    Python内置函数.png

    31、hex()

    a)描述

    原文:
    Return the hexadecimal representation of an integer.
    中文:
    返回一个整数的十六进制表示形式。

    b)语法

    hex 语法:hex(x)

    c)参数

    x:一个整数

    d)返回值

    返回一个字符串,以 0x 开头。

    e)实例
    print("hex(255):",hex(255))
    print("hex(-42):",hex(-42))
    print("hex(12):",hex(12))
    print("type(hex(12)):",type(hex(12)))
    

    运行结果:

    hex(255): 0xff
    hex(-42): -0x2a
    hex(12): 0xc
    type(hex(12)): <class 'str'>     # 字符串
    

    32、id()

    a)描述

    原文:
    Return the identity of an object.
    This is guaranteed to be unique among simultaneously existing objects.(CPython uses the object's memory address.)
    中文:
    返回对象的标识。
    这保证是唯一的同时存在的对象。(CPython使用对象的内存地址) 。
    诠释:
    id() 函数用于获取对象的内存地址。

    b)语法

    id 语法:id([object])

    c)参数

    object:对象。

    d)返回值

    返回对象的内存地址。

    e)实例
    a = 'kevin'
    print("id(a):",id(a))
    b = 1
    print("id(b):",id(b))
    

    运行结果:

    id(a): 1740301575472
    id(b): 140706674362016
    

    33、input()

    a)描述

    原文:
    Read a string from standard input. The trailing newline is stripped.
    The prompt string, if given, is printed to standard output without a trailing newline before reading input.
    If the user hits EOF (nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.On nix systems, readline is used if available.
    中文:
    从标准输入读取一个字符串,尾行换行被剥离。
    提示字符串,如果给定,在读取输入之前,不带换行符,打印到标准输出。
    如果用户点击EOF (
    nix: Ctrl-D, Windows: Ctrl-Z+Return),则抛出EOFError。在
    nix系统中,如果可用,则使用readline。
    诠释:
    input() 函数接受一个标准输入数据,返回为 string 类型。
    注意:在 Python3.x 中 raw_input() 和 input() 进行了整合,去除了 raw_input( ),仅保留了input( )函数,其接收任意输入,将所有输入默认为字符串处理,并返回字符串类型。

    b)语法

    input 语法:input([prompt])

    c)参数

    prompt:提示信息

    d)返回值

    返回对应的字符串

    e)实例
    a = input("please input:")
    print("type(a):",type(a))
    b = input("please input:")
    print("type(b):",type(b))
    

    运行结果:

    please input:1228      # 输入整数
    type(a): <class 'str'>         # 字符串
    please input:kevin         # 输入字符串
    type(b): <class 'str'>        # 字符串
    

    34、int()

    a)描述

    int() 函数用于将一个字符串或数字转换为整型。

    b)语法

    int() 方法的语法:class int(x, base=10)

    c)参数

    x:字符串或数字。
    base:进制数,默认十进制。
    x 有两种:str / int
    1、若 x 为纯数字,则不能有 base 参数,否则报错;其作用为对入参 x 取整。

    print("",int(3.1415926))
    print("",int(-11.123))
    print("",int(2.5))
    print("",int(2.5,10))
    

    运行结果:

     3
     -11
     2
    Traceback (most recent call last):
      File "D:/Python_Project/Temp.py", line 1251, in <module>
        print("",int(2.5,10))
    TypeError: int() can't convert non-string with explicit base
    

    2、若 x 为 str,则 base 可略可有。
    base 存在时,视 x 为 base 类型数字,并将其转换为 10 进制数字。
    若 x 不符合 base 规则,则报错。

    print('int("9"):',int("9"))    # 默认10进制
    print('int("1001",2):',int("1001",2))   # "1001"才是2进制格式,并转化为十进制数字9
    print('int("0xa",16):',int("0xa",16))   # ≥16进制才会允许入参为a,b,c...
    print('int("123",8):',int("123",8))   # 视123为8进制数字,对应的10进制为83
    

    运行结果:

    int("9"): 9
    int("1001",2): 9
    int("0xa",16): 10
    int("123",8): 83
    

    报错1:

    print('int("9",2):',int("9",2))  # 报错,因为2进制无9
    

    运行结果:

    Traceback (most recent call last):
      File "D:/Python_Project/Temp.py", line 1254, in <module>
        print('int("9",2):',int("9",2))  # 报错,因为2进制无9
    ValueError: invalid literal for int() with base 2: '9'
    

    报错2:

    print('int("3.14",8):',int("3.14",8))   # 报错,str须为整数
    

    运行结果:

    Traceback (most recent call last):
      File "D:/Python_Project/Temp.py", line 1255, in <module>
        print('int("3.14",8):',int("3.14",8))   # 报错,str须为整数
    ValueError: invalid literal for int() with base 8: '3.14'
    

    报错3:

    print('int("1.2"):',int("1.2"))    # 报错,str须为整数
    

    运行结果:

    Traceback (most recent call last):
      File "D:/Python_Project/Temp.py", line 1256, in <module>
        print('int("1.2"):',int("1.2"))    # 报错,str须为整数
    ValueError: invalid literal for int() with base 10: '1.2'
    

    报错4:

    print('int("b",8):',int("b",8))     # 报错
    

    运行结果:

    Traceback (most recent call last):
      File "D:/Python_Project/Temp.py", line 1257, in <module>
        print('int("b",8):',int("b",8))     # 报错
    ValueError: invalid literal for int() with base 8: 'b'
    
    d)返回值

    返回整型数据。

    e)实例
    print("int():",int())               # 不传入参数时,得到结果0
    print("int(3):",int(3))
    print("int(3.6):",int(3.6))
    print("int('12',16):",int('12',16))        # 如果是带参数base的话,12要以字符串的形式进行输入,12 为 16进制
    print("int('0xa',16):",int('0xa',16))
    print("int('10',8):",int('10',8))
    

    运行结果:

    int(): 0
    int(3): 3
    int(3.6): 3
    int('12',16): 18
    int('0xa',16): 10
    int('10',8): 8
    

    35、 isinstance()

    a)描述

    原文:
    Return whether an object is an instance of a class or of a subclass thereof.
    A tuple, as in isinstance(x, (A, B, ...)), may be given as the target to check against. This is equivalent to isinstance(x, A) or isinstance(x, B) or ... etc.
    中文:
    返回对象是类的实例还是类的子类的实例。
    一个元组,如isinstance(x, (A, B,…),可以作为检查的目标。这相当于isinstance(x, A)或isinstance(x, B)或…等等。
    诠释:
    isinstance() 函数来判断一个对象是否是一个已知的类型,类似 type()。
    isinstance() 与 type() 区别:
    type() 不会认为子类是一种父类类型,不考虑继承关系。
    isinstance() 会认为子类是一种父类类型,考虑继承关系。
    如果要判断两个类型是否相同推荐使用 isinstance()。

    b)语法

    isinstance() 方法的语法:isinstance(object, classinfo)

    c)参数

    object:实例对象。
    classinfo:可以是直接或间接类名、基本类型或者由它们组成的元组,对于基本类型来说 classinfo 可以是:int,float,bool,complex,str(字符串),list,dict(字典),set,tuple。

    d)返回值

    如果对象的类型与参数二的类型(classinfo)相同则返回 True,否则返回 False。

    e)实例

    实例1:

    a = 2
    print("isinstance (a,int):",isinstance (a,int))
    print("isinstance (a,str)",isinstance (a,str))
    print("isinstance (a,(str,int,list)):",isinstance (a,(str,int,list)))    # 是元组中的一个返回 True
    

    运行结果:

    isinstance (a,int): True
    isinstance (a,str) False
    isinstance (a,(str,int,list)): True
    

    实例2(type() 与 isinstance()区别):

    class A:
        pass
    class B(A):
        pass
    print("isinstance(A(), A):",isinstance(A(), A))
    print("type(A()) == A:",type(A()) == A)
    print("isinstance(B(), A):",isinstance(B(), A))
    print("type(B()) == A:",type(B()) == A)
    

    运行结果:

    isinstance(A(), A): True
    type(A()) == A: True
    isinstance(B(), A): True
    type(B()) == A: False
    

    36、issubclass()

    a)描述

    原文:
    Return whether 'cls' is a derived from another class or is the same class.
    A tuple, as in issubclass(x, (A, B, ...)), may be given as the target to check against. This is equivalent to issubclass(x, A) or issubclass(x, B) or ... etc.
    中文:
    返回“cls”是派生自另一个类还是同一个类。
    A tuple, as in issubclass(x, (A, B,…)),可以作为检查的目标。这相当于issubclass(x, A)或issubclass(x, B)或…等等。
    诠释:
    issubclass() 方法用于判断参数 class 是否是类型参数 classinfo 的子类。

    b)语法

    issubclass() 方法的语法:issubclass(class, classinfo)

    c)参数

    class:类。
    classinfo:类。

    d)返回值

    如果 class 是 classinfo 的子类返回 True,否则返回 False。

    e)实例
    class A:
        pass
    class B(A):
        pass
    class C:
        pass
    print("issubclass(B, A):",issubclass(B, A))
    print("issubclass(C, A):",issubclass(C, A))
    

    运行结果:

    issubclass(B, A): True
    issubclass(C, A): False
    

    37、iter()

    a)描述

    原文:
    iter(iterable) -> iterator
    iter(callable, sentinel) -> iterator
    Get an iterator from an object. In the first form, the argument must supply its own iterator, or be a sequence.
    In the second form, the callable is called until it returns the sentinel.
    中文:
    iter(iterable) ->iterator
    iter(callable, sentinel) ->iterator
    从一个对象获得一个迭代器。在第一种形式中,参数必须提供自己的迭代器,或者是一个序列。
    在第二种形式中,可调用项被调用,直到它返回标记。

    b)语法

    iter() 方法的语法:iter(object[, sentinel])

    c)参数

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

    d)返回值

    迭代器对象。

    e)实例
    lst = [1, 2, 3]
    for i in iter(lst):
        print(i)
    

    运行结果:

    1
    2
    3
    

    38、len()

    a)描述

    原文:
    Return the number of items in a container.
    中文:
    返回容器中元素的个数。
    诠释:
    len() 返回对象(字符、列表、元组等)长度或项目个数。实参可以是序列(如 string、bytes、tuple、list 或 range 等)或集合(如 dictionary、set 或 frozen set 等)。len()不是字符串类的方法。

    b)语法

    len()方法语法:len( s )

    c)参数

    s:对象。

    d)返回值

    返回对象长度

    e)实例
    str = "kevin"
    print("len(str):",len(str))             # 字符串长度
    l = [1,2,3,4]
    print("len(l):",len(l))
    

    运行结果:

    len(str): 5
    len(l): 4
    

    39、list()

    a)描述

    list() 方法用于将元组或字符串转换为列表。
    注:元组与列表是非常类似的,区别在于元组的元素值不能修改,元组是放在括号中,列表是放于方括号中。

    b)语法

    list()方法语法:list(seq)

    c)参数

    seq:要转换为列表的元组或字符串。

    d)返回值

    返回列表。

    e)实例
    aTuple = (123, 'Google', 'Kevin', 'Taobao')
    list1 = list(aTuple)
    print ("list1列表元素 : ", list1)
    str="Hello World"
    list2=list(str)
    print ("list2列表元素 : ", list2)
    

    运行结果:

    list1列表元素 :  [123, 'Google', 'Kevin', 'Taobao']
    list2列表元素 :  ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
    

    40、locals()

    a)描述

    原文:
    Return a dictionary containing the current scope's local variables.
    NOTE: Whether or not updates to this dictionary will affect name lookups in the local scope and vice-versa is implementation dependent and not covered by any backwards compatibility guarantees.
    中文:
    返回一个包含当前作用域的局部变量的字典。
    注意:对这个字典的更新是否会影响本地范围内的名称查找,反之亦然,这取决于实现,并且没有任何向后兼容性保证。
    诠释:
    locals() 函数会以字典类型返回当前位置的全部局部变量。
    对于函数, 方法, lambda 函式, 类, 以及实现了 call 方法的类实例, 它都返回 True。

    b)语法

    locals() 函数语法:locals()

    c)参数

    d)返回值

    返回字典类型的局部变量。

    e)实例
    def kevin(arg):    # 两个局部变量:arg、z
        z = 1
        print(locals())
    kevin(4)
    

    运行结果:

    {'arg': 4, 'z': 1}
    

    相关文章

      网友评论

        本文标题:Python内置函数(4)

        本文链接:https://www.haomeiwen.com/subject/rrbwfhtx.html