常用内置函数及用法:
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 []