Python3.6.x中内置函数总结及讲解
Python3.6.x中内置函数总结
#-*-coding:utf-8-*-
"""
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()
"""
fromcollectionsimportIterator,Iterable
#abs(x)
#求绝对值
print(abs(-1),abs(1))
#all(iterable)
#如果iterable的所有元素都为真,则返回True(iterable为空,返回True)
print(all([1,'a',[2]]))#True
print(all([0,'a',[]]))#False
print(all(''))#True
#any(iterable)
#只要iterable中有一个元素为真,则返回True(iterable为空,返回False)
print(any([1,[],'']))#True
print(any([0,0.0,'',[],{},set()]))#False
print(any([]))#False
#ascii(s)
#只在Python3中支持,用于在不支持Unicode的平台查看Unicode字符串
#就像repr()那样,创建对象的可打印形式,但在结果中只是用ascii字符,非ascii字符都转换为合适的转义序列。
print(ascii('hello你好'))
#'hello\u4f60\u597d'
#repr(obj)
#将其它类型数据转换为字符串,支持大部分内置数据类型
print(repr(123))#123
print(repr('hello你好'))#'hello你好'
print(repr([1,2,3]))#[1,2,3]
print(repr({'a':1}))#{'a':1}
print(repr(object()))#
#str(value='',encoding=None,errors='strict')
#转换为字符串
print(str())#''
print(str(666))#666
print(str(6.66))#6.66
print(str(b'666'))#b'666'
#bin(x)
#返回一个字符串,其中包含整数x的二进制形式0b1010
print(bin(0),bin(1),bin(10))
#0b00b10b1010
#classbool([x])
#是class,返回True或False
print(bool(),bool(0),bool(1),bool(''),bool('abc'),bool([]),bool([1]),bool(False),bool(True))
#FalseFalseTrueFalseTrueFalseTrueFalseTrue
#classbytearray(source=None,encoding=None,errors='strict')
#返回一个字节数组,字符范围[0,255]
print(bytearray("hello你好","utf-8"))
#bytearray(b'hello\xe4\xbd\xa0\xe5\xa5\xbd')
#bytes(value=b'',encoding=None,errors='strict')
#返回字节类型,字符范围[0,255]
print(bytes("hello你好","utf-8"))
#b'hello\xe4\xbd\xa0\xe5\xa5\xbd'
#callable(o)
#返回True或者False,判断一个给定对象o是否是可调用对象
print(callable(1),callable(''),callable(str))
#FalseFalseTrue
#chr(x)
#返回Unicode编码表中整数x对应的字符
print(chr(65),chr(20001))
#A両
#ord()
#返回单个字符在Unicode码表中对应的整数编码
print(ord('A'),ord('李'),ord('永'),ord('平'))#65264462770424179
#@classmethod()
#将一个普通函数转换为类方法,等价于@classmethond装饰器
classA():
deffunc01(*args):
print('classmethod()',*args)
classmethod(func01)
@classmethod
deffunc02(clz,*args):
print('@classmethond',*args)
A.func01()
A.func02()
#输出
#classmethod()
#@classmethond
#@staticmethod
#将一个普通函数转换为静态方法
classA():
deffunc01(*args):
print('staticmethod()',*args)
staticmethod(func01)
@staticmethod
deffunc02(*args):
print('@staticmethod',*args)
A.func01()
A.func02()
#输出
#staticmethod()
#@staticmethod
#compile(source,filename,mode,flags=0,dont_inherit=False,optimize=-1)
#将字符串格式的源代码,编译为可以被exec()或eval()函数执行的代码code对象
#source:一个Python模块或多个代码块,或者是单一代码块,或者是一个表达式
#filename:运行时错误消息提示
#mode:与source对应,模块或多个代码块--"exec",单一代码块--"single",表达式--"eval"
statements="""
print('-'*50)
num=3
whilenum:
print("hello")
num-=1
print('-'*50)"""
filename="run-timeerror"
codes=compile(source=statements,filename=filename,mode="exec")
print(type(codes))
#eval(codes)
exec(codes)
#输出
#
#--------------------------------------------------
#hello
#hello
#hello
#--------------------------------------------------
#eval(expression,globals=None,locals=None)
#运行Python表达式字符串或者是经过compile()编译后生成的code对象
#obj可以是字符串对象或者已经由compile编译过的代码对象,
#globals和locals是可选的,分别代表了全局和局部名称空间中的对象,其中globals必须是字典,而locals是任意的映射对象
print(eval("2**3"))#8
print(eval("type({'key':'value'})"))#
#exec(object[,globals[,locals]])
#运行Python代码字符串或者是经过compile()编译后生成的code对象
statements="""
num=1
ifnum<3:
print("1<3")"""
exec(statements)#1<3
exec('print("exec")')#exec
#classcomplex(real,imag=None)
#返回复数
c=complex(1,2)
print(c,c.real,c.imag)
c=complex('1+2j')
#c=complex('1+2j')#报错ValueError,字符串中不能包含空格
#c=complex('1+2i')#报错ValueError,复数虚部必须使用英文字母j表示
print(c,c.real,c.imag)
#输出
#(1+2j)1.02.0
#(1+2j)1.02.0
#delattr(obj,attr)
#等价于delobj.attr
#删除对象obj的attr属性
classA:
attr_01=1
attr_02=2
print(A.attr_01)
delattr(A,'attr_01')
#print(A.attr_01)#AttributeError:typeobject'A'hasnoattribute'attr_01'
print(A.attr_02)
delA.attr_02
#print(A.attr_02)#AttributeError:typeobject'A'hasnoattribute'attr_02'
#classdict(**kwarg)
#classdict(mapping,**kwarg)
#classdict(iterable,**kwarg)
#返回一个字典对象
print(dict())#{}
print(dict(a=2,b=1))#{'b':1,'a':2}
print(dict([('a',1),('b',2),('c',3)]))#{'a':1,'b':2,'c':3}
print(dict({'a':'A','b':'B'}))#{'a':'A','b':'B'}
#dir(obj)
#参数为空,返回当前作用域中的属性和方法列表
#参数不为空,返回参数对象obj的作用域中的属性和方法列表
#参数不为空,且该参数对象所属类中重载了__dir__(self)运算符,则返回__dir__(self)的返回值
print(dir())
print(dir(int))
print(dir(dict))
classB():
def__dir__(self):
return['哼','哈']
deffunc(self):
pass
b=B()
print(dir(b))#['哈','哼']
#divmod(a,b)
#等价于(a//b,a%b)
#返回长除法的商与余数组成的元组
print(divmod(10,3),(10//3,10%3))
print(divmod(10,3.0),(10//3.0,10%3.0))
print(divmod(10.0,3),(10.0//3,10.0%3))
#(3,1)(3,1)
#(3.0,1.0)(3.0,1.0)
#(3.0,1.0)(3.0,1.0)
#enumerate(i,start=0)
#根据给定iterable,返回枚举类型对象,是iterator类型
print(list(enumerate('abc',start=1)))
foriteminenumerate('123',start=0):
print(item)
#输出
#[(1,'a'),(2,'b'),(3,'c')]
#(0,'a')
#(1,'b')
#(2,'c')
#filter(function,iterable)
#过滤序列中的值
#filter函数将序列iterable中的每一个元素传入函数function中,如果返回值为真,则添加到结果集中;否则,过滤掉
#如果function为None,则将iterable中值为True的元素添加到结果集中
data=[-1,0,1,2,3,False]
res=filter(lambdax:x>=0,data)
print(res)#
print(list(res))#[0,1,2,3,False]
res=filter(None,data)
print(list(res))#[-1,1,2,3]
#classfloat([x])
#生成浮点数,x为数字或者字符串
#inf:无穷
print(float(),float(1),float('1'),float('+1.23'),float('+1E6'),float('-Infinity'),float('-12345\n'))
#0.01.01.01.231000000.0-inf-12345.0
#format(value,[format_spec])
#格式化显示value的值,类型为str
#如果format_spec为空,则等效于str(value)
print(format(123))#123
print(format(True))#True
print(format({'a':1,'b':2}))#{'a':1,'b':2}
print(format(123,'b'))#格式化为2进制1111011
print(format(123,'o'))#格式化为8进制173
print(format(123,'d'))#格式化为10进制123
print(format(123,'x'))#格式化为16进制,使用小写字母显示7b
print(format(123,'X'))#格式化为16进制,使用大写在木显示7B
print(format(123456789.123456789,'e'))#科学计数法,默认保留6位小数1.234568e+08
print(format(123456789.123456789,'0.2e'))#科学计数法,保留2位小数1.23e+08
print(format(123456789.123456789,'E'))#科学计数法,1.234568E+08
print(format(123456789.123456789,'0.2E'))#科学计数法,1.23E+08
print(format(123456789.123456789,'f'))#小数点计数法,默认保留6位小数,123456789.123457
print(format(123456789.123456789,'0.2f'))#小数点计数法,保留2位小数,123456789.12
print(format(1.0e+1000,'F'),format(-1.0e+1000,'F'))#小数点计数法,无穷大转换为字母INF,-INF
#classset([iterable])
#获取一个set实例对象,可变,元素不重复
print(set())#set()
print(set('123'))#{'2','3','1'}
#classfrozenset([iterable])
#返回一个frozenset实例对象,不可变,元素不重复
print(frozenset())#frozenset()
print(frozenset('123'))#frozenset({'2','3','1'})
#getattr(object,name[,default])
#返回object的name属性值,name必须是str类型
#如果不存在name属性,设置了default返回default值,否则,抛出异常AttributeError
classA(object):
attr_01='value_01'
print(getattr(A,'attr_01'))
print(getattr(A,'attr_02','value_02'))
#print(getattr(A,'attr_03'))#AttributeError:typeobject'A'hasnoattribute'attr_03'
#hasattr(object,name)
#判断object是否拥有属性name,返回True或False
print(hasattr(A,'attr_01'))#True
print(hasattr(A,'attr_02'))#False
#setattr(object,name,value)
#给object设置属性name,值为value
setattr(A,'attr_02','value_02')
print(hasattr(A,'attr_02'))#True
#globals()
#返回属于全局作用域的属性或者方法的字典表
print(globals())
#locals()
#返回属于本地作用域的属性和方法的字典表
print(locals())
deffunction():
a,b=1,2
print(locals())#{'b':2,'a':1}
function()
#vars(object)
#返回任意对象的__dict__属性,前提是存在该属性
print(vars(int))
#hash(object)
#返回object的哈希值,大小相等的数字,哈希值一定相同
print(hash(1),hash(1.0))
print(hash(A),hash(A()))
print(hash(int),hash(hash))
#help([object])
#调用内置的帮助系统
#object可以为空,module,function,class,method,keyword,ordocumentationtopi
#help()
#importre
#help(re)
#help(hash)
#help('class')
#classint(x=0)
#classint(x,base=10)
#将给定数据x从base进制转换为10进制int
#x为数字或可转换为数字的字符串,base为数字x本来的进制
print(int(255))#255
print(int('255'))#255
print(int('255',base=10))#255
print(int('255',base=8))#173
#oct(x)
#将10进制数x转换为8进制数
print(oct(255))#0o377
#hex(x)
#将一个int类型的数字转换为16进制
print(hex(255),hex(0))#0xff0x0
#id()
#返回代表object身份的一个int数字,可以认为C语言中"对象的内存地址"
print(id(0))
print(id(id))
#input([prompt])
#接收用户的输入并返回字符串
#value=input('--->')
#print(value)
#print(*objects,sep='',end='\n',file=sys.stdout,flush=False)
#*args:任意多个字符串
#sep:字符串之间的分割符,默认为空格
#end:结束符号,默认为换行\n
print('a','b','c',sep='$',end='\n\n')
#isinstance(object,classinfo)
#判断object是否是classinfo的一个实例
classA():pass
print(isinstance(1,int))#True
print(isinstance(A(),A))#True
#issubclass(class,classinfo)
#判断class是否是classinfo的一个子类
classA():pass
classB(A):pass
print(issubclass(B,A))#True
#iter(object[,sentinel])
#将一个可迭代对象转换为迭代器Iterator
i=iter('abc')
print(type(i))
#next(iterator[,default])
#返回迭代器的下一个元素
#如果没有下一个,返回default参数,如果没有default,抛出StopIteration异常
print(next(i),next(i),next(i))
#print(next(i))#StopIteration
print(next(i,'没有更多元素了'))
#len(iterable)
#返回iterable的元素个数
print(len('abc'))#3
print(len([1,2,3]))#3
print(len((1,2,3)))#3
print(len({'a':1}))#1
print(len({1,2,3}))#3
#classlist([iterable])
#实例化一个list对象
print(list())
print(list('abcd'))
print(list(range(5)))
#map(function,iterable,...)
#在序列中映射函数:map函数会对一个序列对象中的每一个元素应用被传入的函数,并返回一个包含所有函数调用结果的映射集合
#res=map(lambdax:x,[1,2,3])
res=map(lambdax,y:x+y,[1,2,3],[4,5,6])
print(type(res))
print(list(res))
#max()
#返回给定序列中的最大值
print(max(1,2))#2
print(max([1,2]))#2
print(max({'a':2,'b':1}))#b
print(max({'a','b'}))#b
#min()
#返回给定序列中的最小值
print(min(1,2))#1
print(min([1,2]))#1
print(min({'a':2,'b':1}))#a
print(min({'a','b'}))#a
#memoryview(object)
#什么鬼?内存视图?C中的指针?
view=memoryview(b'abcd')
print(view[0])#97
#classobject
#返回一个object
print(object)#
print(object())#
#open(file,mode='r',buffering=-1,encoding=None,errors=None,newline=None,closefd=True,opener=None)
#打开一个文件对象
#pow(x,y,[z])
#2个参数时,等效于x**y
#3个参数时,等效于x**y%z
print(pow(10,3))#1000
print(pow(10,3,3))#1
#classproperty(fget=None,fset=None,fdel=None,doc=None)
#不懂?
#range([start,]stop[,sep])
#生成数字列表
r=range(5)
print(type(r),isinstance(r,Iterator))#False
foriinrange(1,10,2):
print(i,end='')#13579
print('\n')
#reversed(seq)
#翻转序列seq,返回Iterator
i=reversed(['a','b','c'])
print(i)
print(next(i),next(i),next(i),next(i,'没有了'))
#round(number[,ndigits])
#四舍五入
#ndigits为保留小数点位数,默认为0
print(round(16),round(16.18),round(8.88),round(-8.88))#16169-9
print(round(16,1),round(16.18,1),round(8.88,1),round(-8.88,1))#1616.28.9-8.9
#classslice(stop)¶
#classslice(start,stop[,step])
#返回一个切片slice对象,表示步距,可用于切片操作,实际上对可迭代对象的切片操作就是调用了slice方法
print(slice(5))#slice(None,5,None)
print(slice(1,5))#slice(1,5,None)
print(slice(1,5,2))#slice(1,5,2)
seq='abcdefghj'
print(seq[slice(5)])#abcde
print(seq[slice(1,5,2)])#bd
#sorted(iterable,*,key=None,reverse=False)
#对可迭代对象进行排序
#key为函数,依次作用于每个元素
#reverse为是否倒序排序
print(sorted('872Aadbc',key=None,reverse=True))
#['d','c','b','a','A','8','7','2']
print(sorted('872Aadbc',key=lambdax:str.lower(x),reverse=True))
#['d','c','b','A','a','8','7','2']
#sum(iterable[,start])
#求和:iterable中各元素之和,加上第二个参数start的值
#第二个参数start默认为0
print(sum([1,2,3]))
print(sum([1,2,3],10))
#super([type[,object-or-type]])
#调用父类中的方法
classA(object):
defmethond(self):
print('----A----')
classB(A):
defmethond(self):
super(B,self).methond()
#等价于
#super().methond()
print('----B----')
B.methond(B())
#tuple([iterable])
#返回一个元祖对象,不可变的list
print(tuple(['L','O','V','E','E']))
#type(obj)
#返回obj的数据类型
print(type(0))
print(type(''))
print(type([]))
print(type((0,)))
print(type({}))
#zip()
#创建一个迭代器,结果为俩个Iterable中各元素从开始位置开始的映射关系
#如果2个Iterable中的元素个数不同,则舍弃比较多的元素
ziped=zip('abcd','1234')
print(isinstance(ziped,Iterator))#True
print(list(ziped))#[('a','A'),('b','B'),('c','C'),('d','D')]
ziped=zip('abc','1234')
print(list(ziped))#[('a','1'),('b','2'),('c','3')]
ziped=zip('abcd','123')
print(list(ziped))#[('a','1'),('b','2'),('c','3')]
print(list(zip('abc')))#[('a',),('b',),('c',)]
print(list(zip('abc','')))#[]
#__import__(name,globals=None,locals=None,fromlist=(),level=0)
#不常用的高级函数
#importimportlib
#importlib.import_module('module_name')
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。如果你想了解更多相关内容请查看下面相关链接