zoukankan      html  css  js  c++  java
  • Python常用内置类和常用内置函数汇总

    一:内置类:
    (1)常用内置类
    1,class int(object)
    :
    """
    int(x=0) -> integer
    int(x, base=10) -> integer

    Convert a number or string to an integer, or return 0 if no arguments
    are given. If x is a number, return x.__int__(). For floating point
    numbers, this truncates towards zero.

    If x is not a number or if base is given, then x must be a string,
    bytes, or bytearray instance representing an integer literal in the
    given base. The literal can be preceded by '+' or '-' and be surrounded
    by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
    Base 0 means to interpret the base from the string as an integer literal.
    >>> int('0b100', base=0)
    4
        它使用C中的long实现,拥有准确的精度,此外布尔类型是整数的子类型
        """
    2,class float(object):
    """
    float(x) -> floating point number

    Convert a string or number to a floating point number, if possible.
    浮点数使用C中的double实现,Python放弃了单精度浮点型,float总是不精确的,所以不要用于金钱

    """
    3,class bool(int):
    """
    bool(x) -> bool

    Returns True when the argument x is true, False otherwise.
    The builtins True and False are the only two instances of the class bool.
    The class bool is a subclass of the class int, and cannot be subclassed.
    """
    4,class enumerate(object):
    """
    enumerate(iterable[, start]) -> iterator for index, value of iterable

    Return an enumerate object. iterable must be another object that supports
    iteration. The enumerate object yields pairs containing a count (from
    start, which defaults to zero) and a value yielded by the iterable argument.
    enumerate is useful for obtaining an indexed list:
    (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
      for example:
      l =[5,9,8,4,5,6,2,1]
      for index ,val in enumerate(l):
      print(index,val)
        """
    5,class zip(object):
    """
    zip(iter1 [,iter2 [...]]) --> zip object

    Return a zip object whose .__next__() method returns a tuple where
    the i-th element comes from the i-th iterable argument. The .__next__()
    method continues until the shortest iterable in the argument sequence
    is exhausted and then it raises StopIteration.
    >>>
      a = [1,2,3]
      b = [4,5,6]
      c = [7,8,9]

      d = zip(a,b,c)
      print(d) #<zip object at 0x0000025FEA07A848>
      # print(list(d)) #[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

      对一个字典排序:

      方法一:给lambda 赋值,改变list.sort() 排序依据
      d ={"tom":18,"jane":19,"jack":10}
      # 可以用lambda 排序
      l = list(d.items())
      l.sort(key=lambda x:x[1])
      print(l)
      方法二:
      #利用zip 对字典按值排序
      d ={"tom":18,"jane":19,"jack":10}
      d_zipped = zip(d.values(),d.keys())
      l = list(d_zipped)
      l.sort()
      print(l)
      
      ########### l.sort(,key = ,reversed=)
      而sorted(iterable,key = ,reversed=)  ,sorted() 和l.sort() 的区别是sorted() 不改变原来列表,而l.sort() 改变原列表

      
      一般我们是要保留原始数据的,所以还是采用sorted() 吧!
      d ={"tom":18,"jane":19,"jack":10}
      l= list(d.items())
      l_new = sorted(l,key=lambda x:x[1])
      print(l_new)
        """
      方法三:(推荐!)
      d ={"tom":18,"jane":19,"jack":10}
      #sorted给key 排序,但是排序依据被我们修改为d[k]
      d = sorted(d,key=lambda k:d[k]) #返回一个列表
      print(d)
      但是缺点是 val 取不出来,前两种都可以直接得到val

    6,class reversed(object):
    """
    reversed(sequence) -> reverse iterator over values of the sequence

    Return a reverse iterator #得到一个逆序迭代器!
      
      l = [1,5,6,9,8]
      l_new = reversed(l)
      print(l_new.__next__()) #8
      #l.reverse() 是改变原数据的
        """
    7,class slice(object):
    """
    slice(stop)
    slice(start, stop[, step])

    Create a slice object. This is used for extended slicing (e.g. a[0:10:2]).
      
      l = [1,2,5,3,6,5,8,7,8,9,10]
      a = slice(3,5)
      print(l[a]) #[3, 6]
      print(a.start) #3
      print(a.stop) #5
      print(a.step) #None
      #当然也可以使用l[3:5]
      #只是用对象的方式更好的使用切片
      


    """
    class complex(object): 
        """
    complex(real[, imag]) -> complex number

    Create a complex number from a real part and an optional imaginary part.
    This is equivalent to (real + imag*1j) where imag defaults to 0.
    复数由实数与虚数构成,是数的概念扩展,在数值的后面加 'J' 或 'j' 进行定义,不常用
    """



    (2)所有内置类继承的结构:
    class object:
    """ The most base type """
    class BaseException(object):
    """ Common base class for all exceptions """

    class Exception(BaseException):
    """ Common base class for all non-exit exceptions. """
    class ArithmeticError(Exception):  #算术错误
    """ Base class for arithmetic errors. """
    class AssertionError(Exception):
    """ Assertion failed. """
    class AttributeError(Exception):
    """ Attribute not found. """
    class WindowsError(Exception):
    """ Base class for I/O related errors. """
    OSError = WindowsError
    IOError = WindowsError
    EnvironmentError = WindowsError


    class BlockingIOError(OSError):
    """ I/O operation would block. """
    class int(object):
    """
    int(x=0) -> integer
    int(x, base=10) -> integer

    Convert a number or string to an integer, or return 0 if no arguments
    are given. If x is a number, return x.__int__(). For floating point
    numbers, this truncates towards zero.

    If x is not a number or if base is given, then x must be a string,
    bytes, or bytearray instance representing an integer literal in the
    given base. The literal can be preceded by '+' or '-' and be surrounded
    by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
    Base 0 means to interpret the base from the string as an integer literal.
    >>> int('0b100', base=0)
    4
    """
    class bool(int):
    """
    bool(x) -> bool

    Returns True when the argument x is true, False otherwise.
    The builtins True and False are the only two instances of the class bool.
    The class bool is a subclass of the class int, and cannot be subclassed.
    """
    class ConnectionError(OSError):
    """ Connection error. """
    class BrokenPipeError(ConnectionError):
    """ Broken pipe. """
    class BufferError(Exception):
    """ Buffer error. """
    class bytearray(object):  #字节数组
    """
    bytearray() 方法返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256。


    bytearray(iterable_of_ints) -> bytearray
    bytearray(string, encoding[, errors]) -> bytearray
    bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer
    bytearray(int) -> bytes array of size given by the parameter initialized with null bytes
    bytearray() -> empty bytes array

    Construct a mutable bytearray object from:
    - an iterable yielding integers in range(256)
    - a text string encoded using the specified encoding
    - a bytes or a buffer object
    - any object implementing the buffer API.
    - an integer
    >>>bytearray() bytearray(b'')
       >>> bytearray([1,2,3]) bytearray(b'x01x02x03')
       >>> bytearray('runoob', 'utf-8') bytearray(b'runoob')


    """
    class bytes(object):
    """
    bytes(iterable_of_ints) -> bytes
    bytes(string, encoding[, errors]) -> bytes
    bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
    bytes(int) -> bytes object of size given by the parameter initialized with null bytes
    bytes() -> empty bytes object

    Construct an immutable array of bytes from:
    - an iterable yielding integers in range(256)
    - a text string encoded using the specified encoding
    - any object implementing the buffer API.
    - an integer
    """
    class Warning(Exception):
    """ Base class for warning categories. """
    class BytesWarning(Warning):
    """
    Base class for warnings about bytes and buffer related problems, mostly
    related to conversion from str or comparing to str.
    """
    class ChildProcessError(OSError):
    """ Child process error. """
    
    
    class classmethod(object):
    """
    classmethod(function) -> method

    Convert a function to be a class method.

    A class method receives the class as implicit first argument,
    just like an instance method receives the instance.
    To declare a class method, use this idiom:

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

    It can be called either on the class (e.g. C.f()) or on an instance
    (e.g. C().f()). The instance is ignored except for its class.
    If a class method is called for a derived class, the derived class
    object is passed as the implied first argument.

    Class methods are different than C++ or Java static methods.
    If you want those, see the staticmethod builtin.
      """
    class complex(object):
    """
    complex(real[, imag]) -> complex number

    Create a complex number from a real part and an optional imaginary part.
    This is equivalent to (real + imag*1j) where imag defaults to 0.
    """
    class ConnectionAbortedError(ConnectionError):
    """ Connection aborted. """
    class ConnectionRefusedError(ConnectionError):
    """ Connection refused. """
    class ConnectionResetError(ConnectionError):
    """ Connection reset. """
    class DeprecationWarning(Warning):
    """ Base class for warnings about deprecated features. """
    class dict(object):
    """
    dict() -> new empty dictionary
    dict(mapping) -> new dictionary initialized from a mapping object's
    (key, value) pairs
    dict(iterable) -> new dictionary initialized as if via:
    d = {}
    for k, v in iterable:
    d[k] = v
    dict(**kwargs) -> new dictionary initialized with the name=value pairs
    in the keyword argument list. For example: dict(one=1, two=2)
    """
    class enumerate(object):
    """
    enumerate(iterable[, start]) -> iterator for index, value of iterable

    Return an enumerate object. iterable must be another object that supports
    iteration. The enumerate object yields pairs containing a count (from
    start, which defaults to zero) and a value yielded by the iterable argument.
    enumerate is useful for obtaining an indexed list:
    (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
    """
    class EOFError(Exception):
    """ Read beyond end of file. """
    class FileExistsError(OSError):
    """ File already exists. """
    class FileNotFoundError(OSError):
    """ File not found. """
    class filter(object):
    """
    filter(function or None, iterable) --> filter object

    Return an iterator yielding those items of iterable for which function(item)
    is true. If function is None, return the items that are true.
    """
    class float(object):
    """
    float(x) -> floating point number

    Convert a string or number to a floating point number, if possible.
    """
    class FloatingPointError(ArithmeticError):
    """ Floating point operation failed. """
    class frozenset(object):
    """
    frozenset() -> empty frozenset object
    frozenset(iterable) -> frozenset object

    Build an immutable unordered collection of unique elements.
    """
    class FutureWarning(Warning):
    """
    Base class for warnings about constructs that will change semantically
    in the future.
    """
    class GeneratorExit(BaseException):
    """ Request that a generator exit. """
    class ImportError(Exception):
    """ Import can't find module, or can't find name in module. """
    class ImportWarning(Warning):
    """ Base class for warnings about probable mistakes in module imports """
    class SyntaxError(Exception): # 语法错误
    """ Invalid syntax. """
    class IndentationError(SyntaxError): #缩进错误
    """ Improper indentation. """
    class LookupError(Exception):
    """ Base class for lookup errors. """
    class IndexError(LookupError):
    """ Sequence index out of range. """
    class InterruptedError(OSError):
    """ Interrupted by signal. """
    class IsADirectoryError(OSError):
    """ Operation doesn't work on directories. """
    class KeyboardInterrupt(BaseException):
    """ Program interrupted by user. """
    class KeyError(LookupError):
    """ Mapping key not found. """
    class list(object):
    """
    list() -> new empty list
    list(iterable) -> new list initialized from iterable's items
    """
    class map(object):
    """
    map(func, *iterables) --> map object

    Make an iterator that computes the function using arguments from
    each of the iterables. Stops when the shortest iterable is exhausted.
    """
    class MemoryError(Exception):
    """ Out of memory. """
    class memoryview(object):
    """ Create a new memoryview object which references the given object. """
    class NameError(Exception):
    """ Name not found globally. """
    class NotADirectoryError(OSError):
    """ Operation only works on directories. """
    class RuntimeError(Exception):
    """ Unspecified run-time error. """
    class NotImplementedError(RuntimeError):
    """ Method or function hasn't been implemented yet. """
    class OverflowError(ArithmeticError):
    """ Result too large to be represented. """
    class PendingDeprecationWarning(Warning):
    """
    Base class for warnings about features which will be deprecated
    in the future.
    """
    class PermissionError(OSError):
    """ Not enough permissions. """
    class ProcessLookupError(OSError):
    """ Process not found. """
    class property(object):
    """
    property(fget=None, fset=None, fdel=None, doc=None) -> property attribute

    fget is a function to be used for getting an attribute value, and likewise
    fset is a function for setting, and fdel a function for del'ing, an
    attribute. Typical use is to define a managed attribute x:

    class C(object):
    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.")

    Decorators make defining new properties or modifying existing ones easy:

    class C(object):
    @property
    def x(self):
    "I am the 'x' property."
    return self._x
    @x.setter
    def x(self, value):
    self._x = value
    @x.deleter
    def x(self):
    del self._x
    """
    class range(object):
    """
    range(stop) -> range object
    range(start, stop[, step]) -> range object

    Return an object that produces a sequence of integers from start (inclusive)
    to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.
    start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.
    These are exactly the valid indices for a list of 4 elements.
    When step is given, it specifies the increment (or decrement).
    """
    class RecursionError(RuntimeError):
    """ Recursion limit exceeded. """
    class ReferenceError(Exception):
    """ Weak ref proxy used after referent went away. """
    class ResourceWarning(Warning):
    """ Base class for warnings about resource usage. """
    class reversed(object):
    """
    reversed(sequence) -> reverse iterator over values of the sequence

    Return a reverse iterator
    """
    class RuntimeWarning(Warning):
    """ Base class for warnings about dubious runtime behavior. """
    class set(object):
    """
    set() -> new empty set object
    set(iterable) -> new set object

    Build an unordered collection of unique elements.
    """
    class slice(object):
    """
    slice(stop)
    slice(start, stop[, step])

    Create a slice object. This is used for extended slicing (e.g. a[0:10:2]).
    """
    class staticmethod(object):
    """
    staticmethod(function) -> method

    Convert a function to be a static method.

    A static method does not receive an implicit first argument.
    To declare a static method, use this idiom:

    class C:
    def f(arg1, arg2, ...): ...
    f = staticmethod(f)

    It can be called either on the class (e.g. C.f()) or on an instance
    (e.g. C().f()). The instance is ignored except for its class.

    Static methods in Python are similar to those found in Java or C++.
    For a more advanced concept, see the classmethod builtin.
    """
    class StopAsyncIteration(Exception):
    """ Signal the end from iterator.__anext__(). """
    class StopIteration(Exception):
    """ Signal the end from iterator.__next__(). """
    class str(object):
    """
    str(object='') -> str
    str(bytes_or_buffer[, encoding[, errors]]) -> str

    Create a new string object from the given object. If encoding or
    errors is specified, then the object must expose a data buffer
    that will be decoded using the given encoding and error handler.
    Otherwise, returns the result of object.__str__() (if defined)
    or repr(object).
    encoding defaults to sys.getdefaultencoding().
    errors defaults to 'strict'.
    """
    class super(object):
    """
    super() -> same as super(__class__, <first argument>)
    super(type) -> unbound super object
    super(type, obj) -> bound super object; requires isinstance(obj, type)
    super(type, type2) -> bound super object; requires issubclass(type2, type)
    Typical use to call a cooperative superclass method:
    class C(B):
    def meth(self, arg):
    super().meth(arg)
    This works for class methods too:
    class C(B):
    @classmethod
    def cmeth(cls, arg):
    super().cmeth(arg)
    """
    class SyntaxWarning(Warning):
    """ Base class for warnings about dubious syntax. """
    class SystemError(Exception):
    """
    Internal error in the Python interpreter.

    Please report this to the Python maintainer, along with the traceback,
    the Python version, and the hardware/OS platform and version.
    """
    class SystemExit(BaseException):
    """ Request to exit from the interpreter. """
    class TabError(IndentationError):
    """ Improper mixture of spaces and tabs. """
    class TimeoutError(OSError):
    """ Timeout expired. """
    class tuple(object):
    """
    tuple() -> empty tuple
    tuple(iterable) -> tuple initialized from iterable's items

    If the argument is a tuple, the return value is the same object.
    """
    class type(object):
    """
    type(object_or_name, bases, dict)
    type(object) -> the object's type
    type(name, bases, dict) -> a new type
    """
    class TypeError(Exception):
    """ Inappropriate argument type. """
    class UnboundLocalError(NameError):
    """ Local name referenced but not bound to a value. """
    class ValueError(Exception):
    """ Inappropriate argument value (of correct type). """
    class UnicodeError(ValueError):
    """ Unicode related error. """
    class UnicodeDecodeError(UnicodeError):  #解码
    """ Unicode decoding error. """
    class UnicodeEncodeError(UnicodeError):  #编码
    """ Unicode encoding error. """
    class UnicodeTranslateError(UnicodeError):
    """ Unicode translation error. """
    class UnicodeWarning(Warning):
    """
    Base class for warnings about Unicode related problems, mostly
    related to conversion problems.
    """
    class UserWarning(Warning):
    """ Base class for warnings generated by user code. """
    class ZeroDivisionError(ArithmeticError):
    """ Second argument to a division or modulo operation was zero. """
    class zip(object):
    """
    zip(iter1 [,iter2 [...]]) --> zip object

    Return a zip object whose .__next__() method returns a tuple where
    the i-th element comes from the i-th iterable argument. The .__next__()
    method continues until the shortest iterable in the argument sequence
    is exhausted and then it raises StopIteration.
    """
    class __loader__(object):
    """
    Meta path import for built-in modules.

    All methods are either class or static methods to avoid the need to
    instantiate the class.
    """
    
    

     二:内置函数

    1), 重要的三个:map() ,reduce() ,filter() 

    #=================================================
    #=====================map=========================
    #=================================================
    #map() 对每个元素都计算
    #内置函数map () 我们先看下面的程序
    # def func(arr):
    # ret = []
    # for i in arr:
    # ret.append(i**2)
    # return ret
    #
    # ret = func([1,2,3,5,4,7])
    # print(ret)
    #此时如果突然想改变逻辑,i + 1 然后再添加到ret 中,只能重新写了,这样不好
    #==========================================
    # def abstract_func(func,arr):
    # ret = []
    # for i in arr:
    # ret.append(func(i)) #将i 进行相应的运算之后加到ret
    # return ret
    #
    # def square(i):
    # return i**2
    #
    # l = [1,4,6,5,4,2,3,5]
    # ret = abstract_func(square,l)
    # print(ret)
    # #此时如果想换逻辑运算,比如加1
    # def add_one(i):
    # return i+1
    # ret = abstract_func(add_one,l)
    # print(ret)

    #============================================
    #第二个方案已经很好了,但是我们知道匿名函数,所以我们用匿名函数取代里面的计算逻辑
    l = [1,4,6,5,4,2,3,5]
    def abstract_func(func,arr):
    ret = []
    for i in arr:
    ret.append(func(i))
    return ret
    ret = abstract_func(lambda x:x**2,l)
    # print(ret)
    ret = abstract_func(lambda x:x+1,l)
    # print(ret)
    #这就更加完美了,perfect !

    #=================================================
    #内置函数 map()
    ret = map(lambda x:x+1,l) #当然第一个参数,传的不是匿名函数也是可以的, 第二个参数是可迭代对象
    # print(ret) #map 的内部会做循环的。 <map object at 0x0000021911F5B2E8>
    # print(list(ret)) #将map 对象变为列表 [2, 5, 7, 6, 5, 3, 4, 6]



    #=================================================
    #=====================filter======================
    #=================================================
    #过滤出指定的元素
    #另一个内置函数filter()
    ls_name = ["tom_sb","jack_sb","jane_sb","sb_richel"]
    # def func(list):
    # ret = []
    # for name in list:
    # if name.endswith("sb"):
    # ret.append(name)
    # return ret
    # ret = func(ls_name)
    # print(ret)
    #输出:['tom_sb', 'jack_sb', 'jane_sb']
    #此时如果想看谁是以sb 开头的,所以不太好
    #==================================================
    def abstract_func(func,list):
    ret = []
    for name in list:
    if func(name):
    ret.append(name)
    return ret
    def end_sb(name):
    return name.endswith("sb")
    ret = abstract_func(end_sb,ls_name)
    # print(ret) #['tom_sb', 'jack_sb', 'jane_sb']
    def start_sb(name):
    return name.startswith("sb")
    ret = abstract_func(start_sb,ls_name)
    # print(ret) #['sb_richel']
    #====================================
    #和上面一样,这样就写活了
    #和上面也一样,可以使用lambda匿名函数
    ret = abstract_func(lambda x:x.startswith("sb"),ls_name)
    # print(ret) #['sb_richel']
    ret = abstract_func(lambda x:x.endswith("sb"),ls_name)
    # print(ret) #['tom_sb', 'jack_sb', 'jane_sb']
    #==========================牛逼
    #终于可以引出内置函数filter() 了
    ret= filter(lambda x:x.startswith("sb"),ls_name)
    # print(ret) #<filter object at 0x000001C21F64B2E8>
    # print(list(ret)) #['sb_richel']
    ret = filter(lambda x:x.endswith("sb"),ls_name)
    # print(list(ret)) #['tom_sb', 'jack_sb', 'jane_sb']

    #=================================================
    #=====================reduce======================
    #=================================================
    ls = [1,5,56,8,7,8,9,4,2,1,4]
    # def func(arr):
    # res = 0
    # for num in arr:
    # res +=num
    # return res
    # ret = func(ls)
    # print(ret) #105
    #现在想求累乘
    #不太好
    #===============================================
    # def abstract_func(func,arr):
    # res = 1
    # for num in arr:
    # res = func(res,num)
    # return res
    #但是res = 1 就写死了
    #===============================================
    # 改进:
    def abstract_func(func,arr):
    pop_num = arr.pop(0) #将第一个弹出来,并赋值给res
    res = pop_num
    for num in arr:
    res = func(res,num)
    arr.insert(0,pop_num) #恢复数据,不能随意修改原始数据
    return res
    # ret = abstract_func(lambda x,y:x+y,ls) #累加
    #print(ret) #105
    # ret = abstract_func(lambda x,y:x*y,ls) #累乘
    # print(ret) #36126720

    #=============================================
    #如果再给个初始值
    def abstract_func(func,arr,init_val = None):
    if init_val != None:
    res = init_val
    else:
    pop_num = arr.pop(0)
    res = pop_num #将第一个弹出来,并赋值给res
    for num in arr:
    res = func(res,num)
    if init_val == None:
    arr.insert(0,pop_num)
    return res
    ret = abstract_func(lambda x,y:x+y,ls)
    print(ret) #105

    #其实这就是reduce() 函数
    #python2中可以直接使用reduce
    #python3中要引入模块
    from functools import reduce
    ret = reduce(lambda x,y:x+y,ls)
    print(ret) #105
    ret = reduce(lambda x,y:x+y,ls,100)
    print(ret) #205

    #这就是map reduce 和 filter 三个重要的内置函数 注:reduce在python3 中要引入.引入方法是from functools import reduce

     2),其他内置函数:

    abs(x, /):
    Return the absolute value of the argument.
    all(iterable, /): 
    Return True if bool(x) is True for all values x in the iterable。
    If the iterable is empty, return True
       print(all([1,2,3])) #True
       print(all([0,1,2])) #False
    any(iterable, /): 
    """
    Return True if bool(x) is True for any x in the iterable.

    If the iterable is empty, return False.
    """
    ascii(obj, /): 
    """
    Return an ASCII-only representation of an object.
    ascii() 函数类似 repr() 函数, 返回一个表示对象的字符串,
       但是对于字符串中的非 ASCII 字符则返回通过 repr() 函数使用 x, u 或 U 编码的字符。

    As repr(), return a string containing a printable representation of an
    object, but escape the non-ASCII characters in the string returned by
    repr() using \x, \u or \U escapes. This generates a string similar
    to that returned by repr() in Python 2.
    """
    bin(number, /): 
    """
    Return the binary representation of an integer.

    >>> bin(2796202)
    '0b1010101010101010101010'
    """
    callable(obj, /): 
    """
    Return whether the object is callable (i.e., some kind of function).

    Note that classes are callable, as are instances of classes with a
    __call__() method.
    """
    chr(i, /):
    """ Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff. """

       compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

    :
    """
    Compile source into a code object that can be executed by exec() or eval().
       这个函数用来编译一段字符串的源码,结果可以生成字节码或者AST(抽像语法树),
    字节码可以使用函数exec()来执行,而AST可以使用eval()来继续编译。

       exec语句用来执行存储在代码对象、字符串、文件中的Python语句,eval语句用来计算存储在代码对象或字符串中的有效的Python表达式,

               而compile语句则提供了字节编码的预编译。

               当然,需要注意的是,使用exec和eval一定要注意安全性问题,尤其是网络环境中,可能给予他人执行非法语句的机会。

        
      eval_code = compile("1+5","",'eval')
      a = eval(eval_code)
      print(a) #6

      exec_code = compile("for i in range(10): print(i)","","exec")
      exec(exec_code)#这个不能用eval ,用exec可以 #0123456789

    """
    delattr(obj, name, /):
    """
    Deletes the named attribute from the given object.

    delattr(x, 'y') is equivalent to ``del x.y''
    """
    dir(...): ->[]
    """
    dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;
    带参数时,返回参数的属性、方法列表。
          如果参数包含方法__dir__(),该方法将被调用。
          如果参数不包含__dir__(),该方法将最大限度地收集参数信息。
    >>>dir() # 获得当前模块的属性列表 ['__builtins__', '__doc__', '__name__', '__package__', 'arr', 'myslice']
    >>> dir([ ]) # 查看列表的方法 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

    """
    divmod(x, y): 
    """ Return the tuple (x//y, x%y).
    return (0, 0)
    eval(source, globals=None, locals=None, /): 
    """
    Evaluate the given source in the context of globals and locals.

    The source may be a string representing a Python expression
    or a code object as returned by compile().
    exec(source, globals=None, locals=None, /): 
    """
    Execute the given source in the context of globals and locals.

    The source may be a string representing one or more Python statements
    or a code object as returned by compile().
    exit(i):
    退出返回状态码
    format(value, format_spec='', /): 
    """

      本函数把值value按format_spec的格式来格式化,然而函数解释format_spec是根据value的类型来决定的,不同的类型有不同的格式化解释。

           当参数format_spec为空时,本函数等同于函数str(value)的方式。

      其实本函数调用时,是把format(value, format_spec)的方式转换为type(value).__format__(format_spec)方式来调用,

           因此在value类型里就查找方法__format__(),如果找不到此方法,就会返回异常TypeError。
        

      例子:

       print(format('helloworld', '<20'))
    print(format('helloworld', '>20'))
    print(format('helloworld', '^20'))

    s = "{:^20}".format("helloworld")
    print(s)
    '''
    输出:
    helloworld
    helloworld
    helloworld
    helloworld
    '''
    参考博客:https://blog.csdn.net/caimouse/article/details/42010849

    """
    getattr(object, name, default=None): 
    """
    getattr(object, name[, default]) -> value
       """ 
    globals()
    Return the dictionary containing the current scope's global variables.

    NOTE: Updates to this dictionary *will* affect name lookups in the current
    global scope and vice-versa.
    hasattr(obj, name, /): 
    """
    Return whether the object has an attribute with the given name.
    hash(obj, /): 
    """
    Return the hash value for the given object.

    help():
        """
       help()进入帮助模式,help(object)查看具体某个对象的帮助文档
    Define the builtin 'help'.

    This is a wrapper around pydoc.help that provides a helpful message
    when 'help' is typed at the Python interactive prompt.

    Calling help() at the Python prompt starts an interactive help session.
    Calling help(thing) prints help for the python object 'thing'.
    """
    hex(number, /):
    """
    Return the hexadecimal representation of an integer.

    >>> hex(12648430)
    '0xc0ffee'
    """
    id(obj, /):
    """
    Return the identity of an object.

    This is guaranteed to be unique among simultaneously existing objects.
    (CPython uses the object's memory address.)
    """
    input(prompt=None, /)
    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.
    isinstance(obj, class_or_tuple, /)
    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.
    issubclass(cls, class_or_tuple, /)
    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.

    iter(...)

    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.
       参考博客:https://blog.csdn.net/sxingming/article/details/51479039

    len(obj, /)
    Return the number of items in a container.
    locals()
    Return a dictionary containing the current scope's local variables.
    max(...)
      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.
      max(iterable, *[, default=obj, key=func]) -> value
      max(arg1, arg2, *args, *[, key=func]) -> value

      With a single iterable argument, return its biggest item. The
      default keyword-only argument specifies an object to return if
      the provided iterable is empty.
      With two or more arguments, return the largest argument.
    
    
    min(...)
      min(iterable, *[, default=obj, key=func]) -> value
      min(arg1, arg2, *args, *[, key=func]) -> value

      With a single iterable argument, return its smallest item. The
      default keyword-only argument specifies an object to return if
      the provided iterable is empty.
      With two or more arguments, return the smallest argument.
    next(...)
      next(iterator[, default])

      Return the next item from the iterator. If default is given and the iterator
      is exhausted, it is returned instead of raising StopIteration.
      With two or more arguments, return the smallest argument.

    oct(number, /):
    """
    Return the octal representation of an integer.

    >>> oct(342391)
    '0o1234567'
    """
    open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): 
    """
    Open file and return a stream. Raise IOError upon failure.

    file is either a text or byte string giving the name (and the path
    if the file isn't in the current working directory) of the file to
    be opened or an integer file descriptor of the file to be
    wrapped. (If a file descriptor is given, it is closed when the
    returned I/O object is closed, unless closefd is set to False.)

    mode is an optional string that specifies the mode in which the file
    is opened. It defaults to 'r' which means open for reading in text
    mode. Other common values are 'w' for writing (truncating the file if
    it already exists), 'x' for creating and writing to a new file, and
    'a' for appending (which on some Unix systems, means that all writes
    append to the end of the file regardless of the current seek position).
    In text mode, if encoding is not specified the encoding used is platform
    dependent: locale.getpreferredencoding(False) is called to get the
    current locale encoding. (For reading and writing raw bytes use binary
    mode and leave encoding unspecified.) The available modes are:

    ========= ===============================================================
    Character Meaning
    --------- ---------------------------------------------------------------
    'r' open for reading (default)
    'w' open for writing, truncating the file first
    'x' create a new file and open it for writing
    'a' open for writing, appending to the end of the file if it exists
    'b' binary mode
    't' text mode (default)
    '+' open a disk file for updating (reading and writing)
    'U' universal newline mode (deprecated)
    ========= ===============================================================

    The default mode is 'rt' (open for reading text). For binary random
    access, the mode 'w+b' opens and truncates the file to 0 bytes, while
    'r+b' opens the file without truncation. The 'x' mode implies 'w' and
    raises an `FileExistsError` if the file already exists.

    Python distinguishes between files opened in binary and text modes,
    even when the underlying operating system doesn't. Files opened in
    binary mode (appending 'b' to the mode argument) return contents as
    bytes objects without any decoding. In text mode (the default, or when
    't' is appended to the mode argument), the contents of the file are
    returned as strings, the bytes having been first decoded using a
    platform-dependent encoding or using the specified encoding if given.

    'U' mode is deprecated and will raise an exception in future versions
    of Python. It has no effect in Python 3. Use newline to control
    universal newlines mode.

    buffering is an optional integer used to set the buffering policy.
    Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
    line buffering (only usable in text mode), and an integer > 1 to indicate
    the size of a fixed-size chunk buffer. When no buffering argument is
    given, the default buffering policy works as follows:

    * Binary files are buffered in fixed-size chunks; the size of the buffer
    is chosen using a heuristic trying to determine the underlying device's
    "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
    On many systems, the buffer will typically be 4096 or 8192 bytes long.

    * "Interactive" text files (files for which isatty() returns True)
    use line buffering. Other text files use the policy described above
    for binary files.

    encoding is the name of the encoding used to decode or encode the
    file. This should only be used in text mode. The default encoding is
    platform dependent, but any encoding supported by Python can be
    passed. See the codecs module for the list of supported encodings.

    errors is an optional string that specifies how encoding errors are to
    be handled---this argument should not be used in binary mode. Pass
    'strict' to raise a ValueError exception if there is an encoding error
    (the default of None has the same effect), or pass 'ignore' to ignore
    errors. (Note that ignoring encoding errors can lead to data loss.)
    See the documentation for codecs.register or run 'help(codecs.Codec)'
    for a list of the permitted encoding error strings.

    newline controls how universal newlines works (it only applies to text
    mode). It can be None, '', ' ', ' ', and ' '. It works as
    follows:

    * On input, if newline is None, universal newlines mode is
    enabled. Lines in the input can end in ' ', ' ', or ' ', and
    these are translated into ' ' before being returned to the
    caller. If it is '', universal newline mode is enabled, but line
    endings are returned to the caller untranslated. If it has any of
    the other legal values, input lines are only terminated by the given
    string, and the line ending is returned to the caller untranslated.

    * On output, if newline is None, any ' ' characters written are
    translated to the system default line separator, os.linesep. If
    newline is '' or ' ', no translation takes place. If newline is any
    of the other legal values, any ' ' characters written are translated
    to the given string.

    If closefd is False, the underlying file descriptor will be kept open
    when the file is closed. This does not work when a file name is given
    and must be True in that case.

    A custom opener can be used by passing a callable as *opener*. The
    underlying file descriptor for the file object is then obtained by
    calling *opener* with (*file*, *flags*). *opener* must return an open
    file descriptor (passing os.open as *opener* results in functionality
    similar to passing None).

    open() returns a file object whose type depends on the mode, and
    through which the standard file operations such as reading and writing
    are performed. When open() is used to open a file in a text mode ('w',
    'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
    a file in a binary mode, the returned class varies: in read binary
    mode, it returns a BufferedReader; in write binary and append binary
    modes, it returns a BufferedWriter, and in read/write mode, it returns
    a BufferedRandom.

    It is also possible to use a string or bytearray as a file for both
    reading and writing. For strings StringIO can be used like a file
    opened in a text mode, and for bytes a BytesIO can be used like a file
    opened in a binary mode.
    """
    ord(c, /): 
    """ Return the Unicode code point for a one-character string. """
    pow(x, y, z=None, /): 
    """
    Equivalent to x**y (with two arguments) or x**y % z (with three arguments)

    Some types, such as ints, are able to use a more efficient algorithm when
    invoked using the three argument form.
    """
    print(*args, sep=' ', end='
    ', file=None):
    """
    print(value, ..., sep=' ', end=' ', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file: a file-like object (stream); defaults to the current sys.stdout.
    sep: string inserted between values, default a space.
    end: string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.
    """
    repr(obj): 
    """

    repr() 函数将对象转化为供解释器读取的形式。返回一个对象的 string 格式。
    Return the canonical string representation of the object.

    For many object types, including most builtins, eval(repr(obj)) == obj.
    >>>s = 'RUNOOB'
    >>> repr(s) "'RUNOOB'"
    >>> dict = {'runoob': 'runoob.com', 'google': 'google.com'};
       >>> repr(dict) "{'google': 'google.com', 'runoob': 'runoob.com'}"



    """
    round(number, ndigits=None): 
    """
    round(number[, ndigits]) -> number

    Round a number to a given precision in decimal digits (default 0 digits).
    This returns an int when called with one argument, otherwise the
    same type as the number. ndigits may be negative.
    """
    setattr(obj, name, value, /)
    """
    Sets the named attribute on the given object to the specified value.

    setattr(x, 'y', v) is equivalent to ``x.y = v''
    """
    sorted(iterable, key=None, reverse=False): 
    """
    Return a new list containing all items from the iterable in ascending order.

    A custom key function can be supplied to customise the sort order, and the
    reverse flag can be set to request the result in descending order.
    """
    sum(iterable, start=0, /)
    """
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers

    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.
    """
    vars(p_object=None): 
    """
    vars([object]) -> dictionary

    Without arguments, equivalent to locals().
    With an argument, equivalent to object.__dict__.
    """
    __import__(name, globals=None, locals=None, fromlist=(), level=0): 
    """
    __import__(name, globals=None, locals=None, fromlist=(), level=0) -> module

    Import a module. Because this function is meant for use by the Python
    interpreter and not for general use it is better to use
    importlib.import_module() to programmatically import a module.

    The globals argument is only used to determine the context;
    they are not modified. The locals argument is unused. The fromlist
    should be a list of names to emulate ``from name import ...'', or an
    empty list to emulate ``import name''.
    When importing a module from a package, note that __import__('A.B', ...)
    returns package A when fromlist is empty, but its submodule B when
    fromlist is not empty. Level is used to determine whether to perform
    absolute or relative imports. 0 is absolute while a positive number
    is the number of parent directories to search relative to the current module.
    """
    
    
  • 相关阅读:
    redis持久化RDB与AOF
    oracle PL/SQL习题
    pl/sql中的三种循环
    转 Oracle Cursor用法总结
    Oracle与MySQL的SQL语句区别
    安装mysql 遇到最后一步卡死解决方案
    Oracle安装
    mysql安装
    sql语句的优先级
    MVC设计模式
  • 原文地址:https://www.cnblogs.com/zach0812/p/11312479.html
Copyright © 2011-2022 走看看