python函数中文手册.docx
《python函数中文手册.docx》由会员分享,可在线阅读,更多相关《python函数中文手册.docx(18页珍藏版)》请在冰豆网上搜索。
python函数中文手册
内置函数
一,文档说明
原始文档来自于pythonv2.7.2
中文译文和用法尚不完全,您可以自由修改和完善,
您可以在文档结尾鸣谢添上您的名字,我们将会感谢您做的
贡献!
二,函数列表
1,取绝对值
abs(x)
Returntheabsolutevalueofanumber.Theargumentmaybeaplainorlongintegerorafloatingpointnumber.Iftheargumentisacomplexnumber,itsmagnitudeisreturned.
如果你不知道绝对值什么意思,那就要补一下小学数学了!
基本用法
2,
all(iterable)
ReturnTrueifallelementsoftheiterablearetrue(oriftheiterableisempty).Equivalentto:
3.
any(iterable)
ReturnTrueifanyelementoftheiterableistrue.Iftheiterableisempty,returnFalse.Equivalentto:
4.
basestring()
Thisabstracttypeisthesuperclassforstrandunicode.Itcannotbecalledorinstantiated,butitcanbeusedtotestwhetheranobjectisaninstanceofstrorunicode.isinstance(obj,basestring)isequivalenttoisinstance(obj,(str,unicode)).
是字符串和字符编码的超类,是抽象类型。
不能被调用或者实例化。
可以用来判断实例是否为字符串或者字符编码。
方法:
5.二进制转换
bin(x)
Convertanintegernumbertoabinarystring.TheresultisavalidPythonexpression.IfxisnotaPythonintobject,ithastodefinean__index__()methodthatreturnsaninteger.
转换成二进制表达
方法:
6.布尔类型
bool([x])
ConvertavaluetoaBoolean,usingthestandardtruthtestingprocedure.Ifxisfalseoromitted,thisreturnsFalse;otherwiseitreturnsTrue.boolisalsoaclass,whichisasubclassofint.Classboolcannotbesubclassedfurther.ItsonlyinstancesareFalseandTrue
布尔类型的转化
用法:
7.二进制数组的转化
bytearray([source[,encoding[,errors]]])
Returnanewarrayofbytes.Thebytearraytypeisamutablesequenceofintegersintherange0<=x<256.Ithasmostoftheusualmethodsofmutablesequences,describedinMutableSequenceTypes,aswellasmostmethodsthatthestrtypehas,seeStringMethods.
Theoptionalsourceparametercanbeusedtoinitializethearrayinafewdifferentways:
Ifitisastring,youmustalsogivetheencoding(andoptionally,errors)parameters;bytearray()thenconvertsthestringtobytesusing().
Ifitisaninteger,thearraywillhavethatsizeandwillbeinitializedwithnullbytes.
Ifitisanobjectconformingtothebufferinterface,aread-onlybufferoftheobjectwillbeusedtoinitializethebytesarray.
Ifitisaniterable,itmustbeaniterableofintegersintherange0<=x<256,whichareusedastheinitialcontentsofthearray.
Withoutanargument,anarrayofsize0iscreated.
8.
callable(object)
ReturnTrueiftheobjectargumentappearscallable,Falseifnot.Ifthisreturnstrue,itisstillpossiblethatacallfails,butifitisfalse,callingobjectwillneversucceed.Notethatclassesarecallable(callingaclassreturnsanewinstance);classinstancesarecallableiftheyhavea__call__()method.
9.数字转化成字符
chr(i)
ReturnastringofonecharacterwhoseASCIIcodeistheintegeri.Forexample,chr(97)returnsthestring'a'.Thisistheinverseoford().Theargumentmustbeintherange[0..255],inclusive;ValueErrorwillberaisedifiisoutsidethatrange.Seealsounichr().
用法:
10.
classmethod(function)
Returnaclassmethodforfunction.
Aclassmethodreceivestheclassasimplicitfirstargument,justlikeaninstancemethodreceivestheinstance.Todeclareaclassmethod,usethisidiom:
11.两两比较
cmp(x,y)
Comparethetwoobjectsxandyandreturnanintegeraccordingtotheoutcome.Thereturnvalueisnegativeifxy.
X小于X输出负(-1),X等于Y输出零(0),X大于Y输出正
(1)
用法:
12.
compile(source,filename,mode[,flags[,dont_inherit]])
CompilethesourceintoacodeorASTobject.Codeobjectscanbeexecutedbyanexecstatementorevaluatedbyacalltoeval().sourcecaneitherbeastringoranASTobject.RefertotheastmoduledocumentationforinformationonhowtoworkwithASTobjects.
13.
complex([real[,imag]])
Createacomplexnumberwiththevaluereal+imag*jorconvertastringornumbertoacomplexnumber.Ifthefirstparameterisastring,itwillbeinterpretedasacomplexnumberandthefunctionmustbecalledwithoutasecondparameter.Thesecondparametercanneverbeastring.Eachargumentmaybeanynumerictype(includingcomplex).Ifimagisomitted,itdefaultstozeroandthefunctionservesasanumericconversionfunctionlikeint(),long()andfloat().Ifbothargumentsareomitted,returns0j.
14.
delattr(object,name)
Thisisarelativeofsetattr().Theargumentsareanobjectandastring.Thestringmustbethenameofoneoftheobject’sattributes.Thefunctiondeletesthenamedattribute,providedtheobjectallowsit.Forexample,delattr(x,'foobar')isequivalenttodel.
15.字典
dict([arg])
Createanewdatadictionary,optionallywithitemstakenfromarg.ThedictionarytypeisdescribedinMappingTypes—dict.
Forothercontainersseethebuiltinlist,set,andtupleclasses,andthecollectionsmodule.
16.很重要的函数,属性输出
dir([object])
Withoutarguments,returnthelistofnamesinthecurrentlocalscope.Withanargument,attempttoreturnalistofvalidattributesforthatobject.
方法
17.
divmod(a,b)
Taketwo(noncomplex)numbersasargumentsandreturnapairofnumbersconsistingoftheirquotientandremainderwhenusinglongdivision.Withmixedoperandtypes,therulesforbinaryarithmeticoperatorsapply.Forplainandlongintegers,theresultisthesameas(aForfloatingpointnumberstheresultis(q,a%b),whereqisusually(a/b)butmaybe1lessthanthat.Inanycaseq*b+a%bisveryclosetoa,ifa%bisnon-zeroithasthesamesignasb,and0<=abs(a%b)18.
enumerate(sequence[,start=0])
Returnanenumerateobject.sequencemustbeasequence,aniterator,orsomeotherobjectwhichsupportsiteration.Thenext()methodoftheiteratorreturnedbyenumerate()returnsatuplecontainingacount(fromstartwhichdefaultsto0)andthecorrespondingvalueobtainedfromiteratingoveriterable.enumerate()isusefulforobtaininganindexedseries:
(0,seq[0]),(1,seq[1]),(2,seq[2])
19.
eval(expression[,globals[,locals]])
Theargumentsareastringandoptionalglobalsandlocals.Ifprovided,globalsmustbeadictionary.Ifprovided,localscanbeanymappingobject.
Changedinversion:
formerlylocalswasrequiredtobeadictionary.
20.
execfile(filename[,globals[,locals]])
Thisfunctionissimilartotheexecstatement,butparsesafileinsteadofastring.Itisdifferentfromtheimportstatementinthatitdoesnotusethemoduleadministration—itreadsthefileunconditionallyanddoesnotcreateanewmodule.
和exec很相似的函数
21.
file(filename[,mode[,bufsize]])
Constructorfunctionforthefiletype,describedfurtherinsectionFileObjects.Theconstructor’sargumentsarethesameasthoseoftheopen()built-infunctiondescribedbelow.
Whenopeningafile,it’spreferabletouseopen()insteadofinvokingthisconstructordirectly.fileismoresuitedtotypetesting(forexample,writingisinstance(f,file)).
22.
filter(function,iterable)
Constructalistfromthoseelementsofiterableforwhichfunctionreturnstrue.iterablemaybeeitherasequence,acontainerwhichsupportsiteration,oraniterator.Ifiterableisastringoratuple,theresultalsohasthattype;otherwiseitisalwaysalist.IffunctionisNone,theidentityfunctionisassumed,thatis,allelementsofiterablethatarefalseareremoved.
Notethatfilter(function,iterable)isequivalentto[itemforiteminiterableiffunction(item)]iffunctionisnotNoneand[itemforiteminiterableifitem]iffunctionisNone.
See()and()foriteratorversionsofthisfunction,includingavariationthatfiltersforelementswherethefunctionreturnsfalse.
23.浮点数值转化
float([x])
用法:
24.
format(value[,format_spec])
Convertavaluetoa“formatted”representation,ascontrolledbyformat_spec.Theinterpretationofformat_specwilldependonthetypeofthevalueargument,howeverthereisastandardformattingsyntaxthatisusedbymostbuilt-intypes:
FormatSpecificationMini-Language.
25
frozenset([iterable])
Returnafrozensetobject,optionallywithelementstakenfromiterable.ThefrozensettypeisdescribedinSetTypes—set,frozenset.
Forothercontainersseethebuiltindict,list,andtupleclasses,andthecollectionsmodule.
26.
getattr(object,name[,default])
Returnthevalueofthenamedattributeofobject.namemustbeastring.Ifthestringisthenameofoneoftheobject’sattributes,theresultisthevalueofthatattribute.Forexample,getattr(x,'foobar')isequivalentto.Ifthenamedattributedoesnotexist,defaultisreturnedifprovided,otherwiseAttributeErrorisraised.
27.全局参数
globals()
Returnadictionaryrepresentingthecurrentglobalsymboltable.Thisisalwaysthedictionaryofthecurrentmodule(insideafunctionormethod,thisisthemodulewhereitisdefined,notthemodulefromwhichitiscalled).
28.
hasattr(object,name)
Returnthehashvalueoftheobject(ifithasone).Hashvaluesareintegers.Theyareusedtoquicklycomparedictionarykeysduringadictionarylookup.Numericvaluesthatcompareequalhavethesamehashvalue(eveniftheyareofdifferenttypes,asisthecasefor1and.
29.
hash(object)
Returnthehashvalueoftheobject(ifithasone).Hashvaluesareintegers.Theyareusedtoquicklycomparedictionarykeysduringadictionarylookup.Numericvaluesthatcompareequalhavethesamehashvalue(eveniftheyareofdifferenttypes,asisthecasefor1and.
30.很重要的帮助函数方法
help([object])
31.十六进制转化
hex(x)
Convertanintegernumber(ofanysize)toahexadecimalstring.TheresultisavalidPythonexpression.
用法:
32.内存地址
id(object)
Returnthe“identity”ofanobject.Thisisaninteger(orlonginteger)whichisguaranteedtobeunique