• Python菜鸟之路:Python基础-内置函数补充


    常用内置函数及用法:

    1. callable()

    def callable(i_e_, some_kind_of_function): # real signature unknown; restored from __doc__
        """检查对象object是否可调用。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功
        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.
        """
        pass

    案例:

    print(callable(0))
    out: False
    
    print(callable("mystring"))
    out: False
    
    def add(a, b):
        return a + b
    print(callable(add))
    out: True
    
    class A:
       def method(self):
          return 0
    print(callable(A))
    out: True
    
    a = A()
    print(callable(a))
    out: False
    
    class B:
        def __call__(self):
            return 0
    print(callable(B))
    out: True
    
    b = B()
    print(callable(b))
    out: True

    2. chr()   返回十进制整数对应的ASCII字符。与ord()作用相反

        ord()  ASCII字符转换为对应十进制。与chr()作用相反

    def chr(*args, **kwargs): # real signature unknown
        """ Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff. """ 取值范围[0, 255]之间的正数
        pass
    
    def ord(*args, **kwargs): # real signature unknown
        """ Return the Unicode code point for a one-character string. """
        pass

    案例:

    1 print(chr(97))
    2 out: a
    3 
    4 print(ord('a'))
    5 out: 97

    3. eval 把字符串当做表达式,执行。有返回值,返回值就是表达式执行的结果

       exec  比eval更牛逼的功能。但是无返回值。只是去执行python代码或者字符串、表达式.如果接收字符串,则编译成python代码并执行。如果接收代码,则执行。

     1 def eval(*args, **kwargs): # real signature unknown
     2     """
     3     Evaluate the given source in the context of globals and locals.
     4     
     5     The source may be a string representing a Python expression
     6     or a code object as returned by compile().
     7     The globals must be a dictionary and locals can be any mapping,
     8     defaulting to the current globals and locals.
     9     If only globals is given, locals defaults to it.
    10     """
    11     pass
    12 
    13 def exec(*args, **kwargs): # real signature unknown
    14     """
    15     Execute the given source in the context of globals and locals.
    16     
    17     The source may be a string representing one or more Python statements
    18     or a code object as returned by compile().
    19     The globals must be a dictionary and locals can be any mapping,
    20     defaulting to the current globals and locals.
    21     If only globals is given, locals defaults to it.
    22     """
    23     pass

    案例:

     1 s = "print(123)"
     2 r = compile(s, "<string>", "exec")
     3 exec(r)
     4 out:123
     5 
     6 s = 'print(123)'
     7 ret = exec(s)
     8 out: 123
     9 print(ret)
    10 out: None
    11 
    12 s = "8*8"
    13 ret = eval(s)
    14 print(ret)
    15 out: 64

    4. compile(source, filename, mode[, flags[, dont_inherit]]) 

      将source编译为代码或者AST对象。代码对象能够通过exec语句来执行或者eval()进行求值。

     1 def compile(*args, **kwargs): # real signature unknown
     2     """
     3     Compile source into a code object that can be executed by exec() or eval().   将source编译为代码或者AST对象。代码对象能够通过exec语句来执行或者eval()进行求值。
     4     
     5     The source code may represent a Python module, statement or expression.
     6     The filename will be used for run-time error messages.
     7     The mode must be 'exec' to compile a module, 'single' to compile a
     8     single (interactive) statement, or 'eval' to compile an expression.
     9     The flags argument, if present, controls which future statements influence
    10     the compilation of the code.
    11     The dont_inherit argument, if true, stops the compilation inheriting
    12     the effects of any future statements in effect in the code calling
    13     compile; if absent or false these statements do influence the compilation,
    14     in addition to any features explicitly specified.
    15     """
    16     pass

    案例:

    1 s = "print(123)"
    2 r = compile(s, "<string>", "exec")
    3 # 如果不传 <string>参数,就需要传递一个"文件名"参数
    4 exec(r)

    扩充知识:statement和expression

      expression是表达式,就是加减乘除等各种运算符号联接起来的式子,statement是语句,如if语句,while,复制语句等。statement里含有expression.

    5. random 生成随机数模块,是一个隐藏的random.Random类的实例的random方法。

    案例1:生成随机字符串+数字

     1 import random
     2 li = []
     3 for i in range(6):
     4     r = random.randrange(0,5)
     5     if r == 2 or r == 4:
     6         num = random.randrange(0,10)
     7         li.append(str(num))
     8     else:
     9         c = random.randrange(65, 91)
    10         li.append(chr(c))
    11 print("".join(li))

    案例2:生成随机验证码

     1 import random
     2 def generate_verification_code(len=6):
     3     ''' 随机生成6位的验证码 '''
     4     # 注意: 可以生成0-9A-Za-z的列表,也可以指定个list,这里很灵活
     5     # 比如: code_list = ['$','*','.','!','@','~','^','*','<'] # list中可以加特殊字符来增加复杂度
     6     code_list = ['$','*','.','!','@','~','^','*','<'] 
     7     for i in range(10): # 0-9数字
     8         code_list.append(str(i))
     9     for i in range(65, 91): # 对应从“A”到“Z”的ASCII码
    10         code_list.append(chr(i))
    11     for i in range(97, 123): #对应从“a”到“z”的ASCII码
    12         code_list.append(chr(i))
    13     myslice = random.sample(code_list, len)  # 从list中随机获取6个元素,作为一个片断返回
    14     verification_code = ''.join(myslice) # list to string
    15     return verification_code
    16 
    17 code = generate_verification_code(12)
    18 print(code)
    19 
    20 out: nf1JKl7j<E^t

    6. dir() 快速获取模块或者函数提供的功能。返回一个功能列表

       help() 查看对象的功能,可以快速打印源码

     1 def dir(p_object=None): # real signature unknown; restored from __doc__
     2     """
     3     dir([object]) -> list of strings
     4     
     5     If called without an argument, return the names in the current scope.
     6     Else, return an alphabetized list of names comprising (some of) the attributes
     7     of the given object, and of attributes reachable from it.
     8     If the object supplies a method named __dir__, it will be used; otherwise
     9     the default dir() logic is used and returns:
    10       for a module object: the module's attributes.
    11       for a class object:  its attributes, and recursively the attributes
    12         of its bases.
    13       for any other object: its attributes, its class's attributes, and
    14         recursively the attributes of its class's base classes.
    15     """
    16     return []
    dir.source

    案例:

    1 print(dir(dict))
    2 
    3 out: ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
      1 print(help(dict))
      2 
      3 out: Help on class dict in module builtins:
      4 
      5 class dict(object)
      6  |  dict() -> new empty dictionary
      7  |  dict(mapping) -> new dictionary initialized from a mapping object's
      8  |      (key, value) pairs
      9  |  dict(iterable) -> new dictionary initialized as if via:
     10  |      d = {}
     11  |      for k, v in iterable:
     12  |          d[k] = v
     13  |  dict(**kwargs) -> new dictionary initialized with the name=value pairs
     14  |      in the keyword argument list.  For example:  dict(one=1, two=2)
     15  |  
     16  |  Methods defined here:
     17  |  
     18  |  __contains__(self, key, /)
     19  |      True if D has a key k, else False.
     20  |  
     21  |  __delitem__(self, key, /)
     22  |      Delete self[key].
     23  |  
     24  |  __eq__(self, value, /)
     25  |      Return self==value.
     26  |  
     27  |  __ge__(self, value, /)
     28  |      Return self>=value.
     29  |  
     30  |  __getattribute__(self, name, /)
     31  |      Return getattr(self, name).
     32  |  
     33  |  __getitem__(...)
     34  |      x.__getitem__(y) <==> x[y]
     35  |  
     36  |  __gt__(self, value, /)
     37  |      Return self>value.
     38  |  
     39  |  __init__(self, /, *args, **kwargs)
     40  |      Initialize self.  See help(type(self)) for accurate signature.
     41  |  
     42  |  __iter__(self, /)
     43  |      Implement iter(self).
     44  |  
     45  |  __le__(self, value, /)
     46  |      Return self<=value.
     47  |  
     48  |  __len__(self, /)
     49  |      Return len(self).
     50  |  
     51  |  __lt__(self, value, /)
     52  |      Return self<value.
     53  |  
     54  |  __ne__(self, value, /)
     55  |      Return self!=value.
     56  |  
     57  |  __new__(*args, **kwargs) from builtins.type
     58  |      Create and return a new object.  See help(type) for accurate signature.
     59  |  
     60  |  __repr__(self, /)
     61  |      Return repr(self).
     62  |  
     63  |  __setitem__(self, key, value, /)
     64  |      Set self[key] to value.
     65  |  
     66  |  __sizeof__(...)
     67  |      D.__sizeof__() -> size of D in memory, in bytes
     68  |  
     69  |  clear(...)
     70  |      D.clear() -> None.  Remove all items from D.
     71  |  
     72  |  copy(...)
     73  |      D.copy() -> a shallow copy of D
     74  |  
     75  |  fromkeys(iterable, value=None, /) from builtins.type
     76  |      Returns a new dict with keys from iterable and values equal to value.
     77  |  
     78  |  get(...)
     79  |      D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.
     80  |  
     81  |  items(...)
     82  |      D.items() -> a set-like object providing a view on D's items
     83  |  
     84  |  keys(...)
     85  |      D.keys() -> a set-like object providing a view on D's keys
     86  |  
     87  |  pop(...)
     88  |      D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
     89  |      If key is not found, d is returned if given, otherwise KeyError is raised
     90  |  
     91  |  popitem(...)
     92  |      D.popitem() -> (k, v), remove and return some (key, value) pair as a
     93  |      2-tuple; but raise KeyError if D is empty.
     94  |  
     95  |  setdefault(...)
     96  |      D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
     97  |  
     98  |  update(...)
     99  |      D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
    100  |      If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
    101  |      If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
    102  |      In either case, this is followed by: for k in F:  D[k] = F[k]
    103  |  
    104  |  values(...)
    105  |      D.values() -> an object providing a view on D's values
    106  |  
    107  |  ----------------------------------------------------------------------
    108  |  Data and other attributes defined here:
    109  |  
    110  |  __hash__ = None
    111 
    112 None
    help.test

    7. divmod(x, y) 得到x/y的商和余数 (商, 余数)

    1 print(divmod(5,4))
    2 
    3 out: (1, 1)

    8. isinstance()  判断对象是谁的实例, 可以向上查找,甚至查找父类的父类。返回True or False

    1 print(isinstance('a', str))
    2 
    3 out: True

    9. globals() 代表所有的全局变量,返回的 dictionary 的任何的改动都会直接影响到全局变量。

        locals()    代表所有的局部变量,返回 dictionary 的函数, 并且在 dictionary 中设置一个值。是一个只读dict

     1 def foo(arg, a):
     2     x = 1
     3     y = 'xxxxxx'
     4     for i in range(10):
     5         j = 1
     6         k = i
     7     print locals()
     8 
     9 
    10 #调用函数的打印结果    
    11 foo(1,2)
    12 out: {'a': 2, 'i': 9, 'k': 9, 'j': 1, 'arg': 1, 'y': 'xxxxxx', 'x': 1}

    10. len  返回对象的长度,python2中按照字节计算  , python3按照字符来计算

    1 print(len("诸葛亮"))
    2 
    3 #python2
    4 out: 9
    5 #python3
    6 out: 3

    11. hash 返回对象的哈希值

    1 print(hash("abc"))
    2 
    3 out: -8810164989165849038

    12. filter 把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。

     1 class filter(object):
     2     """
     3     filter(function or None, iterable) --> filter object
     4     
     5     Return an iterator yielding those items of iterable for which function(item)
     6     is true. If function is None, return the items that are true.
     7     """
     8     def __getattribute__(self, *args, **kwargs): # real signature unknown
     9         """ Return getattr(self, name). """
    10         pass
    11 
    12     def __init__(self, function_or_None, iterable): # real signature unknown; restored from __doc__
    13         pass
    14 
    15     def __iter__(self, *args, **kwargs): # real signature unknown
    16         """ Implement iter(self). """
    17         pass
    18 
    19     @staticmethod # known case of __new__
    20     def __new__(*args, **kwargs): # real signature unknown
    21         """ Create and return a new object.  See help(type) for accurate signature. """
    22         pass
    23 
    24     def __next__(self, *args, **kwargs): # real signature unknown
    25         """ Implement next(self). """
    26         pass
    27 
    28     def __reduce__(self, *args, **kwargs): # real signature unknown
    29         """ Return state information for pickling. """
    30         pass
    filter.source

    案例:

    1 def is_odd(n):
    2     return n % 2 == 1
    3 
    4 print(list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])))
    5 
    6 out: [1, 5, 9, 15]

    13. map 将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回

     1 class map(object):
     2     """
     3     map(func, *iterables) --> map object
     4     
     5     Make an iterator that computes the function using arguments from
     6     each of the iterables.  Stops when the shortest iterable is exhausted. 将迭代对象按照func的方法进行运算逐个,最终返回一个list对象
     7     """
     8     def __getattribute__(self, *args, **kwargs): # real signature unknown
     9         """ Return getattr(self, name). """
    10         pass
    11 
    12     def __init__(self, func, *iterables): # real signature unknown; restored from __doc__
    13         pass
    14 
    15     def __iter__(self, *args, **kwargs): # real signature unknown
    16         """ Implement iter(self). """
    17         pass
    18 
    19     @staticmethod # known case of __new__
    20     def __new__(*args, **kwargs): # real signature unknown
    21         """ Create and return a new object.  See help(type) for accurate signature. """
    22         pass
    23 
    24     def __next__(self, *args, **kwargs): # real signature unknown
    25         """ Implement next(self). """
    26         pass
    27 
    28     def __reduce__(self, *args, **kwargs): # real signature unknown
    29         """ Return state information for pickling. """
    30         pass
    map.source

    案例:

    1 def f(x):
    2     return x * x
    3 
    4 r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
    5 print(list(r))

    14. repr 通过repr执行对象的时候,会自动调用类里边__repr__的方法

     1 print(repr('e'))
     2 print(type(repr('e')))
     3 print(help(str.__repr__))
     4 
     5 out:
     6 'e'
     7 
     8 Help on wrapper_descriptor:
     9 
    10 __repr__(self, /)
    11     Return repr(self).
    12 
    13 None
    14 
    15 <class 'str'>

    15. reversed 反转,调用对象的__reverse__的方法

     1 li = [1,2,3,4,5]
     2 print(list(reversed(li)))
     3 print(help(list.__reversed__(li)))
     4 
     5 out:
     6 [5, 4, 3, 2, 1]
     7 Help on list_reverseiterator object:
     8 
     9 class list_reverseiterator(object)
    10  |  Methods defined here:
    11  |  
    12  |  __getattribute__(self, name, /)
    13  |      Return getattr(self, name).
    14  |  
    15  |  __iter__(self, /)
    16  |      Implement iter(self).
    17  |  
    18  |  __length_hint__(...)
    19  |      Private method returning an estimate of len(list(it)).
    20  |  
    21  |  __next__(self, /)
    22  |      Implement next(self).
    23  |  
    24  |  __reduce__(...)
    25  |      Return state information for pickling.
    26  |  
    27  |  __setstate__(...)
    28  |      Set state information for unpickling.
    29 
    30 None

    16. round(x, n)  返回 x 的小数点四舍五入到n个数字,如果数字有一位小数,遵循5舍6入原则。其余情况,遵循四舍五入原则。

    print(round(4.4))
    print(round(4.5))
    print(round(4.6))
    print("round(80.23456, 2) : ", round(80.23456, 2))
    print("round(100.000056, 3) : ", round(100.000056, 3))
    print("round(-100.000056, 5) : ", round(-100.000056, 5))
    
    out:
    4
    4
    5
    round(80.23456, 2) :  80.23
    round(100.000056, 3) :  100.0
    round(-100.000056, 5) :  -100.00006

    17. slice 切片操作slice(start, [stop], [step]),不如直接用对象本身支持的切片操作,起码对象自身的切片,使用方式上简单。

    1 s = [1,2,3,4,5,6,8]
    2 myslice = slice(2,4)
    3 print(s[myslice])

    18. sorted()  对对象进行排序,返回一个新的对象。与对象本身的sort方法不同,本身的sort直接修改对象本身。

    1 s = [1,4,2,5,3]
    2 print("sorted s out: ", sorted(s))
    3 new_s = sorted(s)
    4 print("origin s :", s)
    5 print("new s create:", new_s)
    6 
    7 s.sort(reverse=True)
    8 print("s is changed:", s)

    19. vars()  无参数的情况等同locals()

    1 class A:
    2     a = 1
    3     b = 'xxxxxx'
    4     def __dict__(self):
    5         x = 1
    6         y = 2
    7 
    8 print(vars(A))
    9 out: {'__doc__': None, '__module__': '__main__', '__dict__': <function A.__dict__ at 0x0000000000B7F598>, 'a': 1, 'b': 'xxxxxx', '__weakref __': <attribute '__weakref__' of 'A' objects>}

    20. zip()  接受任意多个(包括0个和1个)序列作为参数,返回一个tuple列表

     1 x = [1, 2, 3]
     2 y = [4, 5, 6]
     3 z = [7, 8, 9]
     4 
     5 xyz = zip(x, y, z)
     6 print(list(xyz))
     7 out: 
     8 [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
     9 
    10 x = [1, 2, 3]
    11 y = [4, 5, 6, 7]
    12 print(list(zip(x, y)))
    13 out:
    14 [(1, 4), (2, 5), (3, 6)]

    21. 反射的几个内置方法:hasattr(),setattr(),getattr(),delattr()

      反射的概念:利用字符串的形式去对象(模块)中操作(寻找、检查、删除、设置)成员,就是反射

    1)getattr() 获取对象的某个属性或方法,如果default未给出,则语法:getattr(object, name, default=None)

    def getattr(object, name, default=None): # known special case of getattr
        """
        getattr(object, name[, default]) -> value
        
        Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
        When a default argument is given, it is returned when the attribute doesn't
        exist; without it, an exception is raised in that case.
        """
        pass

    代码案例:

    a = []
    
    print(getattr(a, 'append'))
    out: <built-in method append of list object at 0x0000000000703E48>
    print(getattr(a, 'delete','not found'))
    out: not found
    print(getattr(a, 'delete'))
    out: AttributeError: 'list' object has no attribute 'delete'

    2)hasattr()  用于确定一个对象是否具有某个属性。语法:hasattr(object, name) -> bool 判断object中是否有name属性,返回一个布尔值。

    def hasattr(*args, **kwargs): # real signature unknown
        """
        Return whether the object has an attribute with the given name.
        
        This is done by calling getattr(obj, name) and catching AttributeError.
        """
        pass

    代码案例:

    a = []
    print(hasattr(a, 'append'))
    print(hasattr(a, 'delete'))
    
    out:
    True
    False

     

    3)setattr()

    def setattr(x, y, v): # real signature unknown; restored from __doc__
        """
        Sets the named attribute on the given object to the specified value.
        
        setattr(x, 'y', v) is equivalent to ``x.y = v''
        """
        pass

    代码案例:

    class T:
        def __init__(self):
            pass
    a = T()
    setattr(a, "bb", "123")
    print(a.bb)
    
    out: 123

    4)delattr()

    def delattr(x, y): # real signature unknown; restored from __doc__
        """
        Deletes the named attribute from the given object.
        
        delattr(x, 'y') is equivalent to ``del x.y''
        """
        pass

    代码案例:

    class T:
        def __init__(self):
            pass
    a = T()
    setattr(a, "bb", "123")
    print(a.bb)
    delattr(a, "bb")
    print(hasattr(a, "bb"))

    out:
    123
    False

    22. staticmethod,super 待续

    23. property python内置的装饰器,以后补全

    未完,待续!

  • 相关阅读:
    Emacs使用gnus收发邮件时nnfolder相关介绍
    emacs 播放mp3
    你真的会写二分查找吗?
    数独的经典case
    MySQL处理千万级数据查询、分页
    Mysql Replication 机制
    redis位图(bitmap)常用命令的解析
    由浅入深了解线程池之源码初探
    BlockingQueue家族成员一览
    由浅入深了解线程池之初识线程池
  • 原文地址:https://www.cnblogs.com/jishuweiwang/p/5551403.html
Copyright © 2020-2023  润新知