ThischapterexplainsthemeaningoftheelementsofexpressionsinPython.
SyntaxNotes:Inthisandthefollowingchapters,extendedBNFnotationwillbeusedtodescribesyntax,notlexicalanalysis.When(onealternativeof)asyntaxrulehastheform
name::=othernameandnosemanticsaregiven,thesemanticsofthisformofnamearethesameasforothername.
Whenadescriptionofanarithmeticoperatorbelowusesthephrase"thenumericargumentsareconvertedtoacommontype",thismeansthattheoperatorimplementationforbuilt-intypesworksasfollows:
Someadditionalrulesapplyforcertainoperators(e.g.,astringasaleftargumenttothe'%'operator).Extensionsmustdefinetheirownconversionbehavior.
Atomsarethemostbasicelementsofexpressions.Thesimplestatomsareidentifiersorliterals.Formsenclosedinparentheses,bracketsorbracesarealsocategorizedsyntacticallyasatoms.Thesyntaxforatomsis:
Whenanidentifierthattextuallyoccursinaclassdefinitionbeginswithtwoormoreunderscorecharactersanddoesnotendintwoormoreunderscores,itisconsideredaprivatenameofthatclass.
也參考
Moreprecisely,privatenamesaretransformedtoalongerformbeforecodeisgeneratedforthem.Ifthetransformednameislongerthan255characters,implementation-definedtruncationmayhappen.
Thetransformationisindependentofthesyntacticalcontextinwhichtheidentifierisusedbutonlythefollowingprivateidentifiersaremangled:
Thetransformationruleisdefinedasfollows:
Pythonsupportsstringandbytesliteralsandvariousnumericliterals:
Allliteralscorrespondtoimmutabledatatypes,andhencetheobject'sidentityislessimportantthanitsvalue.Multipleevaluationsofliteralswiththesamevalue(eitherthesameoccurrenceintheprogramtextoradifferentoccurrence)mayobtainthesameobjectoradifferentobjectwiththesamevalue.
Aparenthesizedformisanoptionalexpressionlistenclosedinparentheses:
Anemptypairofparenthesesyieldsanemptytupleobject.Sincetuplesareimmutable,thesamerulesasforliteralsapply(i.e.,twooccurrencesoftheemptytuplemayormaynotyieldthesameobject).
Notethattuplesarenotformedbytheparentheses,butratherbyuseofthecomma.Theexceptionistheemptytuple,forwhichparenthesesarerequired---allowingunparenthesized"nothing"inexpressionswouldcauseambiguitiesandallowcommontypostopassuncaught.
Forconstructingalist,asetoradictionaryPythonprovidesspecialsyntaxcalled"displays",eachofthemintwoflavors:
Commonsyntaxelementsforcomprehensionsare:
However,asidefromtheiterableexpressionintheleftmostforclause,thecomprehensionisexecutedinaseparateimplicitlynestedscope.Thisensuresthatnamesassignedtointhetargetlistdon't"leak"intotheenclosingscope.
Theiterableexpressionintheleftmostforclauseisevaluateddirectlyintheenclosingscopeandthenpassedasanargumenttotheimplicitlynestedscope.Subsequentforclausesandanyfilterconditionintheleftmostforclausecannotbeevaluatedintheenclosingscopeastheymaydependonthevaluesobtainedfromtheleftmostiterable.Forexample:[x*yforxinrange(10)foryinrange(x,x+10)].
Toensurethecomprehensionalwaysresultsinacontaineroftheappropriatetype,yieldandyieldfromexpressionsareprohibitedintheimplicitlynestedscope.
在3.6版被加入:Asynchronouscomprehensionswereintroduced.
在3.8版的變更:yieldandyieldfromprohibitedintheimplicitlynestedscope.
在3.11版的變更:Asynchronouscomprehensionsarenowallowedinsidecomprehensionsinasynchronousfunctions.Outercomprehensionsimplicitlybecomeasynchronous.
Alistdisplayisapossiblyemptyseriesofexpressionsenclosedinsquarebrackets:
Asetdisplayisdenotedbycurlybracesanddistinguishablefromdictionarydisplaysbythelackofcolonsseparatingkeysandvalues:
Anemptysetcannotbeconstructedwith{};thisliteralconstructsanemptydictionary.
Adictionarydisplayisapossiblyemptyseriesofdictitems(key/valuepairs)enclosedincurlybraces:
Ifacomma-separatedsequenceofdictitemsisgiven,theyareevaluatedfromlefttorighttodefinetheentriesofthedictionary:eachkeyobjectisusedasakeyintothedictionarytostorethecorrespondingvalue.Thismeansthatyoucanspecifythesamekeymultipletimesinthedictitemlist,andthefinaldictionary'svalueforthatkeywillbethelastonegiven.
Adictcomprehension,incontrasttolistandsetcomprehensions,needstwoexpressionsseparatedwithacolonfollowedbytheusual"for"and"if"clauses.Whenthecomprehensionisrun,theresultingkeyandvalueelementsareinsertedinthenewdictionaryintheordertheyareproduced.
Ageneratorexpressionisacompactgeneratornotationinparentheses:
Toavoidinterferingwiththeexpectedoperationofthegeneratorexpressionitself,yieldandyieldfromexpressionsareprohibitedintheimplicitlydefinedgenerator.
在3.6版被加入:Asynchronousgeneratorexpressionswereintroduced.
defgen():#definesageneratorfunctionyield123asyncdefagen():#definesanasynchronousgeneratorfunctionyield123Duetotheirsideeffectsonthecontainingscope,yieldexpressionsarenotpermittedaspartoftheimplicitlydefinedscopesusedtoimplementcomprehensionsandgeneratorexpressions.
在3.8版的變更:Yieldexpressionsprohibitedintheimplicitlynestedscopesusedtoimplementcomprehensionsandgeneratorexpressions.
Allofthismakesgeneratorfunctionsquitesimilartocoroutines;theyyieldmultipletimes,theyhavemorethanoneentrypointandtheirexecutioncanbesuspended.Theonlydifferenceisthatageneratorfunctioncannotcontrolwheretheexecutionshouldcontinueafterityields;thecontrolisalwaystransferredtothegenerator'scaller.
在3.3版的變更:Addedyieldfrom
Theparenthesesmaybeomittedwhentheyieldexpressionisthesoleexpressionontherighthandsideofanassignmentstatement.
TheproposaltoenhancetheAPIandsyntaxofgenerators,makingthemusableassimplecoroutines.
Thissubsectiondescribesthemethodsofageneratoriterator.Theycanbeusedtocontroltheexecutionofageneratorfunction.
在3.12版的變更:Thesecondsignature(type[,value[,traceback]])isdeprecatedandmayberemovedinafutureversionofPython.
Hereisasimpleexamplethatdemonstratesthebehaviorofgeneratorsandgeneratorfunctions:
Theexpressionyieldfrom
Thissubsectiondescribesthemethodsofanasynchronousgeneratoriterator,whichareusedtocontroltheexecutionofageneratorfunction.
Primariesrepresentthemosttightlyboundoperationsofthelanguage.Theirsyntaxis:
Aconsequenceofthisisthatalthoughthe*expressionsyntaxmayappearafterexplicitkeywordarguments,itisprocessedbeforethekeywordarguments(andany**expressionarguments--seebelow).So:
Formalparametersusingthesyntax*identifieror**identifiercannotbeusedaspositionalargumentslotsoraskeywordargumentnames.
Acallalwaysreturnssomevalue,possiblyNone,unlessitraisesanexception.Howthisvalueiscomputeddependsonthetypeofthecallableobject.
Ifitis---
Anewinstanceofthatclassisreturned.
Thecorrespondinguser-definedfunctioniscalled,withanargumentlistthatisonelongerthantheargumentlistofthecall:theinstancebecomesthefirstargument.
Thepoweroperatorbindsmoretightlythanunaryoperatorsonitsleft;itbindslesstightlythanunaryoperatorsonitsright.Thesyntaxis:
Forintoperands,theresulthasthesametypeastheoperandsunlessthesecondargumentisnegative;inthatcase,allargumentsareconvertedtofloatandafloatresultisdelivered.Forexample,10**2returns100,but10**-2returns0.01.
Allunaryarithmeticandbitwiseoperationshavethesamepriority:
Thebinaryarithmeticoperationshavetheconventionalprioritylevels.Notethatsomeoftheseoperationsalsoapplytocertainnon-numerictypes.Apartfromthepoweroperator,thereareonlytwolevels,oneformultiplicativeoperatorsandoneforadditiveoperators:
在3.5版被加入.
The+(addition)operatoryieldsthesumofitsarguments.Theargumentsmusteitherbothbenumbersorbothbesequencesofthesametype.Intheformercase,thenumbersareconvertedtoacommontypeandthenaddedtogether.Inthelattercase,thesequencesareconcatenated.
The-(subtraction)operatoryieldsthedifferenceofitsarguments.Thenumericargumentsarefirstconvertedtoacommontype.
Theshiftingoperationshavelowerprioritythanthearithmeticoperations:
Arightshiftbynbitsisdefinedasfloordivisionbypow(2,n).Aleftshiftbynbitsisdefinedasmultiplicationwithpow(2,n).
Eachofthethreebitwiseoperationshasadifferentprioritylevel:
UnlikeC,allcomparisonoperationsinPythonhavethesamepriority,whichislowerthanthatofanyarithmetic,shiftingorbitwiseoperation.AlsounlikeC,expressionslikea
Comparisonscanbechainedarbitrarily,e.g.,x Formally,ifa,b,c,...,y,zareexpressionsandop1,op2,...,opNarecomparisonoperators,thenaop1bop2c...yopNzisequivalenttoaop1bandbop2cand...yopNz,exceptthateachexpressionisevaluatedatmostonce. Notethataop1bop2cdoesn'timplyanykindofcomparisonbetweenaandc,sothat,e.g.,x Theoperators<,>,==,>=,<=,and!=comparethevaluesoftwoobjects.Theobjectsdonotneedtohavethesametype. Thedefaultbehaviorforequalitycomparison(==and!=)isbasedontheidentityoftheobjects.Hence,equalitycomparisonofinstanceswiththesameidentityresultsinequality,andequalitycomparisonofinstanceswithdifferentidentitiesresultsininequality.Amotivationforthisdefaultbehavioristhedesirethatallobjectsshouldbereflexive(i.e.xisyimpliesx==y). Thebehaviorofthedefaultequalitycomparison,thatinstanceswithdifferentidentitiesarealwaysunequal,maybeincontrasttowhattypeswillneedthathaveasensibledefinitionofobjectvalueandvalue-basedequality.Suchtypeswillneedtocustomizetheircomparisonbehavior,andinfact,anumberofbuilt-intypeshavedonethat. Thefollowinglistdescribesthecomparisonbehaviorofthemostimportantbuilt-intypes. User-definedclassesthatcustomizetheircomparisonbehaviorshouldfollowsomeconsistencyrules,ifpossible: Pythondoesnotenforcetheseconsistencyrules.Infact,thenot-a-numbervaluesareanexamplefornotfollowingtheserules. Forthestringandbytestypes,xinyisTrueifandonlyifxisasubstringofy.Anequivalenttestisy.find(x)!=-1.Emptystringsarealwaysconsideredtobeasubstringofanyotherstring,so""in"abc"willreturnTrue. Theexpressionxandyfirstevaluatesx;ifxisfalse,itsvalueisreturned;otherwise,yisevaluatedandtheresultingvalueisreturned. Theexpressionxoryfirstevaluatesx;ifxistrue,itsvalueisreturned;otherwise,yisevaluatedandtheresultingvalueisreturned. Onecommonusecaseiswhenhandlingmatchedregularexpressions: ifmatching:=pattern.search(data):do_something(matching)Or,whenprocessingafilestreaminchunks: whilechunk:=file.read(9000):process(chunk)Assignmentexpressionsmustbesurroundedbyparentheseswhenusedasexpressionstatementsandwhenusedassub-expressionsinslicing,conditional,lambda,keyword-argument,andcomprehension-ifexpressionsandinassert,with,andassignmentstatements.Inallotherplaceswheretheycanbeused,parenthesesarenotrequired,includinginifandwhilestatements. TheexpressionxifCelseyfirstevaluatesthecondition,Cratherthanx.IfCistrue,xisevaluatedanditsvalueisreturned;otherwise,yisevaluatedanditsvalueisreturned. Atrailingcommaisrequiredonlytocreateaone-itemtuple,suchas1,;itisoptionalinallothercases.Asingleexpressionwithoutatrailingcommadoesn'tcreateatuple,butratheryieldsthevalueofthatexpression.(Tocreateanemptytuple,useanemptypairofparentheses:().) Pythonevaluatesexpressionsfromlefttoright.Noticethatwhileevaluatinganassignment,theright-handsideisevaluatedbeforetheleft-handside. Inthefollowinglines,expressionswillbeevaluatedinthearithmeticorderoftheirsuffixes: Operator 描述 (expressions...), [expressions...],{key:value...},{expressions...} Bindingorparenthesizedexpression,listdisplay,dictionarydisplay,setdisplay x[index],x[index:index],x(arguments...),x.attribute Subscription,slicing,call,attributereference Awaitexpression ** +x,-x,~x Positive,negative,bitwiseNOT +,- Additionandsubtraction <<,>> Shifts & BitwiseAND ^ BitwiseXOR | BitwiseOR Comparisons,includingmembershiptestsandidentitytests BooleanNOT BooleanAND BooleanOR Conditionalexpression Lambdaexpression := Assignmentexpression 註解 Ifxisveryclosetoanexactintegermultipleofy,it'spossibleforx//ytobeonelargerthan(x-x%y)//yduetorounding.Insuchcases,Pythonreturnsthelatterresult,inordertopreservethatdivmod(x,y)[0]*y+x%ybeveryclosetox. TheUnicodestandarddistinguishesbetweencodepoints(e.g.U+0041)andabstractcharacters(e.g."LATINCAPITALLETTERA").WhilemostabstractcharactersinUnicodeareonlyrepresentedusingonecodepoint,thereisanumberofabstractcharactersthatcaninadditionberepresentedusingasequenceofmorethanonecodepoint.Forexample,theabstractcharacter"LATINCAPITALLETTERCWITHCEDILLA"canberepresentedasasingleprecomposedcharacteratcodepositionU+00C7,orasasequenceofabasecharacteratcodepositionU+0043(LATINCAPITALLETTERC),followedbyacombiningcharacteratcodepositionU+0327(COMBININGCEDILLA). ThecomparisonoperatorsonstringscompareatthelevelofUnicodecodepoints.Thismaybecounter-intuitivetohumans.Forexample,"\u00C7"=="\u0043\u0327"isFalse,eventhoughbothstringsrepresentthesameabstractcharacter"LATINCAPITALLETTERCWITHCEDILLA". Thepoweroperator**bindslesstightlythananarithmeticorbitwiseunaryoperatoronitsright,thatis,2**-1is0.5. The%operatorisalsousedforstringformatting;thesameprecedenceapplies.