26_Python的内置函数

时间:2023-02-02 22:52:57

The Python interpreter has a number of functions and types built into it that are always available.Python解释器有许多内置的函数和类型,它们总是可用的(全局可调用)。

    内建函数    
abs() dict() help() min() setattr()
all() dir() hex() next() slice()
any() divmod() id() object() sorted()
ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str()
bool() 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()  
delattr() hash() memoryview() set()

作用域相关

globals()——获取全局变量的字典

locals()——获取执行本方法所在命名空间内的局部变量的字典

字符串类型代码的执行(eval、exec、compile)

eval() 执行动态表达式求值

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

eval

exec:执行动态语句块,执行引号里面的内容

 print(exec("1+2+3+4"))     #None
exec("print('hello,world')") #hello,world<br>#除去字符串两边的引号,执行里面的内容(没有返回值),多用于流程语句

exec

compile:将字符串编译为代码或者AST对象,使之能够通过exec语句来执行或者eval进行求值

 #流程语句使用exec
code1 = 'for i in range(0,10): print (i)'
compile1 = compile(code1,'','exec')
exec (compile1) #0 1 2 3 4 5 6 7 8 9 #简单求值表达式用eval
code2 = '1 + 2 + 3 + 4'
compile2 = compile(code2,'','eval')
eval(compile2) #

compile

输入输出相关内置函数

input() 接收用户的输入,默认换行。

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

input

print() 打印输出

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

print

数据类型

type:返回对象的类型

 type(1) # 返回对象的类型  #<class 'int'>

 #使用type函数创建类型D,含有属性InfoD
D = type('D',(A,B),dict(InfoD='some thing defined in D'))
d = D()
d.InfoD #'some thing defined in D'

type

内存相关

id(参数):返回对象的唯一标识符/内存地址

 a = 'some text'
id(a) #

id

hash(参数):返回一个可hash变量的哈希值,不可hash的变量被hash之后会报错。

 t = (1,2,3)
l = [1,2,3]
print(hash(t)) #可hash
print(hash(l)) #会报错 '''
结果:
TypeError: unhashable type: 'list'
'''

hash

文件操作相关

open:使用指定的模式和编码打开文件,返回文件读写对象(文件句柄)

操作文件的模式有r,w,a,r+,w+,a+ 共6种,每一种方式都可以用二进制的形式操作(rb,wb,ab,rb+,wb+,ab+),可以用encoding指定编码,b模式下不用设置encoding.

 with open('log','r',encoding='utf-8') as f_read:
pass #他会返回一个文件句柄

open()

帮助方法

help(内容):返回对象的帮助信息

调用相关

callable(参数):检测对象是否可被调用,如果参数是一个函数名,则会返回True

查看内置属性

dir() 默认查看全局空间内的属性,也接受一个参数,查看这个参数内的方法或变量,并放在一个列表中