26_Python的内置函数
The Python interpreter has a number of functions and types built into it that are always available.Python解释器有许多内置的函数和类型,它们总是可用的(全局可调用)。
作用域相关
globals()——获取全局变量的字典
locals()——获取执行本方法所在命名空间内的局部变量的字典
字符串类型代码的执行(eval、exec、compile)
eval() 执行动态表达式求值

1 print(eval('1+2+3+4')) #10<br><br>#将字符串str对象转化为有效的表达式参与求值运算返回计算结果(除去字符串两边的引号,返回里面的内容)
exec:执行动态语句块,执行引号里面的内容

1 print(exec("1+2+3+4")) #None 2 exec("print('hello,world')") #hello,world<br>#除去字符串两边的引号,执行里面的内容(没有返回值),多用于流程语句
compile:将字符串编译为代码或者AST对象,使之能够通过exec语句来执行或者eval进行求值

1 #流程语句使用exec 2 code1 = 'for i in range(0,10): print (i)' 3 compile1 = compile(code1,'','exec') 4 exec (compile1) #0 1 2 3 4 5 6 7 8 9 5 6 #简单求值表达式用eval 7 code2 = '1 + 2 + 3 + 4' 8 compile2 = compile(code2,'','eval') 9 eval(compile2) #10
输入输出相关内置函数
input() 接收用户的输入,默认换行。

1 s = input("请输入内容 : ") #输入的内容赋值给s变量 2 print(s) #输入什么打印什么。数据类型是str
print() 打印输出

1 def print(self, *args, sep=' ', end='\n', file=None): 2 """ 3 print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) 4 file: 默认是输出到屏幕,如果设置为文件句柄,输出到文件 5 sep: 打印多个值之间的分隔符,默认为空格 6 end: 每一次打印的结尾,默认为换行符 7 flush: 立即把内容输出到流文件,不作缓存 8 """ 9 print(1,2,3) #1 2 3 10 print(1,2,3,sep = '+') #1+2+3 11 print(1,2,3,sep = '+',end = '=?') #1+2+3=?
数据类型
type:返回对象的类型

1 type(1) # 返回对象的类型 #<class 'int'> 2 3 #使用type函数创建类型D,含有属性InfoD 4 D = type('D',(A,B),dict(InfoD='some thing defined in D')) 5 d = D() 6 d.InfoD #'some thing defined in D'
内存相关
id(参数):返回对象的唯一标识符/内存地址

1 a = 'some text' 2 id(a) #2270162138504
hash(参数):返回一个可hash变量的哈希值,不可hash的变量被hash之后会报错。

1 t = (1,2,3) 2 l = [1,2,3] 3 print(hash(t)) #可hash 4 print(hash(l)) #会报错 5 6 ''' 7 结果: 8 TypeError: unhashable type: 'list' 9 '''
文件操作相关
open:使用指定的模式和编码打开文件,返回文件读写对象(文件句柄)
操作文件的模式有r,w,a,r+,w+,a+ 共6种,每一种方式都可以用二进制的形式操作(rb,wb,ab,rb+,wb+,ab+),可以用encoding指定编码,b模式下不用设置encoding.

1 with open('log','r',encoding='utf-8') as f_read: 2 pass 3 4 #他会返回一个文件句柄
帮助方法
help(内容):返回对象的帮助信息
调用相关
callable(参数):检测对象是否可被调用,如果参数是一个函数名,则会返回True
查看内置属性
dir() 默认查看全局空间内的属性,也接受一个参数,查看这个参数内的方法或变量,并放在一个列表中