speakingphp

phpecho  时间:2021-02-13  阅读:()
CopyrightIBMCorporation2010TrademarksPythonbasicsforPHPdevelopersPage1of10PythonbasicsforPHPdevelopersThomasMyerFebruary09,2010AreyouanexperiencedPHPdeveloperwhoneedstolearnPythonThisarticleapproachestheworldofPythondevelopmentfromaPHPdeveloper'sperspective,translatingfamiliarPHPconcepts,suchasvariables,lists,andfunctions,intotheirPythonequivalents.
You'reaPHPdeveloper.
You'veprobablybeenwritingapplicationsforthepastfiveyears(orlonger),andyou'vebuiltjustabouteverythingimaginable—e-commercesystems,simplecontent-managementsystems,TwitterandFacebookintegrations,andahostofcustomutilities.
You'veprobablymaintainedalotofcode,too—everythingfromsimpledisplaypagestocustomapplicationswithtensofthousandsoflinessomebodyelsewrote.
FrequentlyusedacronymsAjax:AsynchronousJavaScript+XMLXML:ExtensibleMarkupLanguageBecauseyou'vespentsomuchtimeworkinginPHP,it'sdoubtfulthatyou'regoingtojumpshiptoanotherlanguage.
Butyoualsoknowthatstandingstillistheonesurerecipefordisasterinthisfield.
Ifnothingelse,learninganewlanguageisliketravelingoverseas:Yougettoseenewthings,tastenewfood,enjoyadifferentculture,havestimulatingconversationswithdifferentpeople,seeneatstuff,thencomebackhometore-evaluateyourusualsurroundings.
ThisarticlegivesyouabitofexposuretoPython.
Itassumesthatyouhavenoknowledgeofthatprogramminglanguage,sosomeofwhatyoureadheremightseemabitbasic.
ItfocusesoncomparingandcontrastingPythonwithPHP—notbecauseonelanguageisbetterthantheotherbutbecauseofasimpletruth:It'softeneasiertolearnnewthingsbyreferringbacktosomethingyoualreadyknow.
Thegoalofthisarticleissimple:togiveyouaquickworkingknowledgeofPythoninthehopethatyou'lldigalittlefurtheronyourown.
Withluck,you'llseethatPythonisn'treallythatdifferentfromwhatyou'reusedto.
Toextendthetravelmetaphor,youaren'treallygoingtoadistantforeignland,justthecountrynextdoorwhereeveryonespeaksthesamelanguageasyou.
WhatisPythonPythonisclassifiedasa"general-purpose,high-levelprogramminglanguage.
"Itisbestknownforbeingincrediblycleanandeasytoread,anditisoneofthefewlanguagesyou'llencounterinwhichwhitespaceandindentationactuallymatter.
Python'sprincipalauthor,GuidoVandeveloperWorksibm.
com/developerWorks/PythonbasicsforPHPdevelopersPage2of10Rossum,isstillveryactiveinthecommunityandhasbeenbestowedthetongue-in-cheektitleof"BenevolentDictatorforLife.
"OneofthenicethingsaboutPythonisitsflexibilityandcompactness.
Itsupportsobject-oriented,structured,aspect-oriented,andfunctionalprogramming,amongotherapproaches.
Pythonwasdesignedwithasmallcoreandalargesetofextensionlibraries,makingthelanguageextremelycompactandflexible.
Fromasyntaxpointofview,you'llfindPythonveryclean—almostmonasticandZen-likeinitssparsity.
PHPdeveloperswilleitherhaveagreatdealofaffectionforthisapproach,findingreliefinthesyntacticaldiscipline,orfinditrestrictive.
Itjustdependsonyouroutlook.
ThePythoncommunityisclearaboutpromotingthisparticularaesthetic,valuingbeautyandsimplicityovercleverhacks.
ThosePHPdevelopers(likemyself)whocameoutofthePerltradition("There'smorethanonewaytodoit")willbeconfrontedwiththetotaloppositephilosophy("Thereshouldonlybeoneobviouswaytodoit").
Infact,thecommunityhasatermforcodethatfollowsapreferredstyle:pythonic.
TosaythatyourcodeispythonicistosaythatisusesPythonidiomswellorthatyou'reshowingnaturalfluencyinthelanguage.
Thisarticledoesn'tbothertryingtobeaPythonista(orPythoneer),butit'ssomethingyouneedtobeawareofifyouwanttocontinuedownthePythonpath.
JustastherearecertainPHP-ishwaystoworkandPerl-ishwaystodothings,takingonPythonmeansthateventually,youneedtostartthinkinginthatlanguage.
Anotherquicknote:PythonwasuptoV3.
0atthetimeofwriting,butthisarticlefocusesonPythonV2.
6.
PythonV3.
0isnotbackward-compatiblewithearlierversions,anditappearsthatV2.
6istheversionmostcommonlyinuse.
Youarefreetousewhateveryouneed,ofcourse.
HowdoesPythondifferfromPHPGenerallyspeaking,PHPisaWebdevelopmentlanguage.
Yes,ithasacommand-lineinterfaceandcanevenbeusedtodevelopembeddedapplications,butforthemostpart,PHPisforWebdevelopment.
Incontrast,PythonisageneralscriptinglanguagethatcanalsobeusedforWebdevelopment.
Inthisway—andIknowI'llbeyelledatforthis—it'sclosertoPerlthanPHP.
(Ofcourse,inallotherways,itcouldn'tbemoredifferent,really.
Butlet'smoveon.
)PHP'ssyntaxislitteredwithdollarsigns($)andcurlybraces({}),whilePythonismorespareandclean.
PHPhasaswitchanddo.
.
.
whileconstruct;Pythondoesn't.
PHPhastheternaryoperator(foobar:baz)andanenormous(andunwieldy)listoffunctionnames,withallkindsofnamingconventions;you'llfindPythonalotcleaner.
PHPhasanarraytypethatdoublesasasasimplelistandadictionaryorhash;Pythonseparatesthetwo.
Pythonalsohasaconceptofmutabilityandimmutability:atuple,forexample,isanimmutablelist.
Youcreateyourtuple,andyoucan'tchangeitafterthat.
Thisconcepttakesabitofgettingusedto,butit'samarvelouswaytoavoiderrors.
Ofcourse,theonlywaytochangeatupleistocopyit,soifyoufindyourselfmakinglotsofchangestoanimmutableobject,youneedtorethinkyourapproach.
ibm.
com/developerWorks/developerWorksPythonbasicsforPHPdevelopersPage3of10Asnoted,indentationinPythonhasmeaning:You'lllearnthisthehardwayinyourfirstfewdayswiththelanguage.
Youcanalsocreatefunctionsandmethodswithkeyword-basedarguments—anicebreakfromthestandardpositionalargumentsyouseeinPHP.
Theobject-orientedpuristswillenjoyPython'strueobjectorientation,and"first-class"classesandfunctions.
Ifyou'reworkingwithnon-Englishlanguages,you'lllovePython'sstronginternationalizationandUnicodesupport.
You'llalsolovePython'smulti-threadingcapabilities;thiswasoneofthefeaturesthatoriginallyattractedme.
Allthisbeingsaid,PHPandPythonaresimilartoeachotherinmanyways.
Youwon'thaveanytroublecreatingvariables,looping,usingconditionals,andcreatingfunctions.
Youwon'tevenhavethatmuchtroublecreatingreusablemodules.
Theusercommunitiesforbothlanguagesareactiveandpassionate.
PHP'sinstalledbaseisalotbigger,butthishasmoretodowithitspopularityonhostingserversanditsWebfocusthananythingelse.
OK—enoughwiththeintromaterial.
Let'sgetdowntocases.
WorkingwithPythonListing1presentsabasicPythonscripttogetyoustarted.
Listing1.
AsimplePythonscriptforiinrange(20):print(i)Listing2showstheinevitableresult.
Listing2.
ResultsofListing1012345678910111213141516171819Let'slookatafewthingsbeforegoinganyfurther,startingwithvariables.
VariablesAsyoucansee,therearenospecialcharacterstodenoteavariable.
Thevariableiisjustplaini—nothingspecial.
Therearenospecialcharacters(likesemicolonsandbraces)todenoteadeveloperWorksibm.
com/developerWorks/PythonbasicsforPHPdevelopersPage4of10codeblockoranendofstatement,either;justasimplecolon(:)ontheforline.
AlsonotethattheindentationtellsPythonwhatbelongstotheforloop.
Forexample,thecodeinListing3printsanoteaftereachnumberintheloop.
Listing3.
Addingastatementtoeachloopforiinrange(20):print(i)print('alldone')Incontrast,thecodeinListing4putsanoteattheendoftheloop.
Listing4.
Addingastatementafteraloopforiinrange(20):print(i)print('alldone!
')Now,thefirsttimeIlookedatsomethinglikethat,Ithoughtitwassheermadness.
WhatTrustnewlinesandindentstokeepmycodenotonlystructuredbutrunningBelieveme,afterawhile,you'llgetusedtoit(althoughIhavetoadmitthatIkeepreachingforthatsemicolonkeytofinishastatement).
Ifyou'reworkingwithotherdevelopersonaPythonproject,you'llfindthisreadabilityahugebonus.
You'llhavealotfewermomentsof,"Nowwhatdidthiscleverfellowtrytodohere"InPHP,youassignavaluetoavariableusingthe=operator(seeListing5).
InPython,youusethesameoperator,exceptthatyou'resaidtolabelorpointtoavalue.
Tome,it'sjustassigning,soIdon'tworrytoomuchaboutthejargon.
Listing5.
Creatingvariablesyorkie='Marlowe'#meetourYorkieMarlowe!
mutt='Kafka'#meetourmuttKafkaprint(mutt)#printsKafkaPythonvariablenameconventionsaresimilartoPHP:Youcanonlyuseletters,numbers,andtheunderscorecharacter(_)whencreatingavariablename.
Likewise,thefirstcharacterofavariablenamecan'tbeanumber.
Pythonvariablenamesarecase-sensitive,andyoucan'tusecertainPythonkeywords(suchasif,else,while,def,or,and,not,in,andis,forstarters)asvariablenames.
Nobigsurprisesthere.
Pythonallowsyoutodoanynumberofstring-basedoperations.
MostoftheoperationsinListing6willbefamiliartoyou.
ibm.
com/developerWorks/developerWorksPythonbasicsforPHPdevelopersPage5of10Listing6.
Commonstring-basedoperationsyorkie='Marlowe'mutt='Kafka'ylen=len(yorkie)#lengthofvariableyorkieprint(ylen)#prints7print(len(yorkie))#doesthesamethinglen(yorkie)#alsodoesthesamething,printisimplicitprint(yorkie.
lower())#lowercasesthestringprint(yorkie.
strip('aeiou'))#removesvowelsfromendofstringprint(mutt.
split('f'))#splits"Kafka"into['Ka','ka']print(mutt.
count('a'))#prints2,thenumberofa'sinstringyorkie.
replace('a','4')#replacea'swith4'sConditionalsYoualreadyknowhowtouseaforloop.
Nowlet'stalkaboutconditionals.
You'llfindthatconditionalsareprettymuchthesameasinPHP:You'llhaveaccesstothefamiliarif/else-typestructuresshowninListing7.
Listing7.
Asimpleconditionaltestyorkie='Marlowe'mutt='Kafka'iflen(yorkie)>len(mutt):print('Theyorkiewins!
')else:print('Themuttwins!
')Youcanalsobuildmorecomplexconditionaltestsusinganif/elif/else(elifbeingtheequivalenttoPHP'selseif),asshowninListing8.
Listing8.
Amorecomplexconditionaltestyorkie='Marlowe'mutt='Kafka'iflen(yorkie)+len(mutt)>15:print('Theyorkieandthemuttwin!
')eliflen(yorkie)+len(mutt)>10:print('Tooclosetotell!
')else:print('Nobodywins!
')Asyoucantell,sofarthere'snothingtooexcitinghere.
It'sallprettymuchwhatyouwouldexpect.
NowlookathowPythonhandleslists;you'llseequiteabitofdifferencebetweenthetwolanguages.
developerWorksibm.
com/developerWorks/PythonbasicsforPHPdevelopersPage6of10ListsOnecommontypeoflistiscalledatuple,andasnoted,it'simmutable.
Onceyouloadatuplewithaseriesofvalues,youcan'tchangeit.
Tuplescancontainnumbers,strings,variables,andevenothertuples.
Tuplesare0-indexed,asyou'dexpect;youcanaccessthelastitemusingthe-1index.
Therearealsoquiteafewfunctionsyoucanrunontuples.
Listing9.
Tuplesitems=(1,mutt,'Honda',(1,2,3))printitems[1]#printsKafkaprintitems[-1]#prints(1,2,3)items2=items[0:2]#items2nowcontains(1,'Kafka')thankstosliceoperation'Honda'initems#returnsTRUElen(items)#returns4items.
index('Kafka')#returns1,becauseseconditemmatchesthisindexlocationListsareliketuples,exceptthatthey'remutable.
Onceyoucreatethem,youcanadd,subtract,andupdatethevaluesinthelist.
Insteadofparentheses(()),youusesquarebrackets,asshowninListing10.
Listing10.
Listsgroceries=['ham','spam','eggs']len(groceries)#returns3printgroceries[1]#printsspamforxingroceries:printx.
upper()#printsHAMSPAMEGGSgroceries[2]='bacon'groceries#listisnow['ham','spam','bacon']groceries.
append('eggs')groceries#listisnow['ham','spam','bacon','eggs']groceries.
sort()groceries#listisnow['bacon','eggs','ham','spam']Adictionaryislikeanassociativearrayorhash:Ituseskey-valuepairstostoreandretrieveinformation.
Butinsteadofbracketsorparentheses,youusecurlybraces.
Likelists,dictionariesaremutable,whichmeansyoucanadd,subtract,andupdatevaluesinthem.
Listing11.
Dictionariescolorvalues={'red':1,'blue':2,'green':3,'yellow':4,'orange':5}colorvalues#prints{'blue':2,'orange':5,'green':3,'yellow':4,'red':1}colorvalues['blue']#prints2colorvalues.
keys()#retrievesallkeysasalist:#['blue','orange','green','yellow','red']colorvalues.
pop('blue')#prints2andremovesthebluekey/valuepaircolorvalues#afterpop,wehave:#{'orange':5,'green':3,'yellow':4,'red':1}ibm.
com/developerWorks/developerWorksPythonbasicsforPHPdevelopersPage7of10CreatingasimplescriptinPythonNowthatyou'vehadabitofexposuretoPython,let'sbuildasimplePythonscript.
ThisscriptreadsthenumberofPHPsessionfilesinyourserver's/tmpdirectory,thenwritesasummaryreporttoalogfile.
Inthisscript,you'regoingtolearnhowtoimportmodulesforspecificfunctions,howtoworkwithfiles,andhowtowritetoalogfile.
You'llalsosetanumberofvariablestokeeptrackoftheinformationyou'vegathered.
Listing12showstheentirescript.
Openaneditor,andpastethecodeintoitandsavethefileastmp.
pysomewhereonyoursystem.
Thenrunchmod+xonthatfiletomakeitexecutable(assumingyou'reonaUNIXsystem).
Listing12.
tmp.
py#!
/usr/bin/pythonimportosfromtimeimportstrftimestamp=strftime("%Y-%m-%d%H:%M:%S")logfile='/path/to/your/logfile.
log'path='/path/to/tmp/directory/'files=os.
listdir(path)bytes=0numfiles=0forfinfiles:iff.
startswith('sess_'):info=os.
stat(path+f)numfiles+=1bytes+=info[6]ifnumfiles>1:title='files'else:title='file'string=stampstr(numfiles)+"session"\+title+","+str(bytes)+"bytes\n"file=open(logfile,"a")file.
writelines(string)file.
close()Onthefirstline,youseewhat'scalledthehash-bangline,whichidentifiesthelocationofthePythoninterpreter.
Onmysystem,it'sat/usr/bin/python.
Adjustthistotheneedsofyoursystem.
Thenexttwolinesimportspecificmodulesthathelpyoudoyourjob.
Giventhatthescriptneedstodealwithfoldersandfiles,youneedtoimporttheosmodule,asitcontainsvariousfunctionsandmethodsthathelpyoulistfiles,readfiles,andworkwithfolders.
You'llalsobewritingtoalogfile,soit'sagoodideatoaddatimestamptoentries—hence,theneedforthetimefunctions.
Youwon'tneedallofthem,sojustimportthestrftimefunction.
developerWorksibm.
com/developerWorks/PythonbasicsforPHPdevelopersPage8of10Inthenextsixlines,yousetvariables.
Thefirst,calledstamp,containsadatestring.
Youusethestrftimefunctiontocreateatimestampwithaspecificformat—inthiscase,astampthatlookslike2010-01-0312:43:03.
Next,createavariablecalledlogfileandputinapathtoafile(itdoesn'tneedtoexistyet)whereyou'llactuallystorelogfilemessages.
Forsimplicity,Iputlogfilesina/logsfolder,butyoucouldputthemanywhere.
Similarly,youneedavariablecalledpaththatcontainsthepathtoyour/tmpdirectory.
Itcanbeanypathyouwantaslongasyouenditwithatrailingslash(/).
Thenextthreevariablesarejustassimple:afileslistthatcontainsallthefilesandfolderslocatedatyourdesignatedpathandtwovariablescalledbytesandnumfiles.
Bothofthosevariablesaresetto0;thescriptincrementsthosevaluesasitprocessesfiles.
Afterallthatcomestheheartofthescript:asimpleforloopthatprocesseseachfileinthefileslist.
Eachtimethroughtheloop,thescriptevaluatesthefilename.
Ifitbeginswithsess_,thenthescriptrunsos.
stat()onthefiletopulloutdataaboutthefile(suchascreationtime,modifytime,andsizeinbytes),incrementsthenumfilescounter,andaddsthenumberofbytesforthisfiletoarunningtotal.
Whentheloopcompletesitsrun,thescriptcheckstoseewhetherthenumfilesvariablecontainsavaluegreaterthan1.
Ifso,itsetsanewvariable,calledtitle,tofiles;otherwise,thetitleissettothesingularformfile.
Thefinalpartofthescriptissimple:Youcreateafinalvariablecalledstring,andinsidethat,youplaceasinglelineofdatathatstartswiththestampandproceedswithnumfiles(convertedtoastring)andthebytes(alsoconvertedtoastring).
Noticethecontinuationcharacter(\);itallowsthecodetoruntothenextline.
It'sagoodtricktoknowforreadability.
Thenyouusetheopen()functiontoopenthelogfileinappendmode(youwanttokeepaddinglinestothefile,afterall),thewritelines()functiontoaddthestringtothelogfile,andtheclose()functiontoclosethefile.
You'venowcreatedasimplePythonscriptyoucandoanythingwith.
Forexample,youcouldsetacronjobtorunthisscriptonceperhourtohelpyoukeeptrackofhowmanyPHPsessionsarebeingusedaroundtheclock.
YoucouldalsousejQueryorsomeotherJavaScriptframeworktohookthisscriptupusingAjaxtogiveyoualog-filefeed(ifso,you'dneedtousetheprintcommandtoreturndata).
ConclusionAsdevelopers,wespendalotoftimeinvestingourselveswithknowledgeaboutspecificlanguagesandapproaches.
Sometimes,doingsoleadstodebatesaboutthesuperiorityofonelanguageoveranother.
I'veparticipatedinmanyofthesedebates,ashavesomeofyou.
Ihavetoadmitthatmostofthesediscussionstendtofallintothesameoldrut—"anythingyoucandoIcandobetter"—whichdoesn'tserveanygoodpurpose.
ibm.
com/developerWorks/developerWorksPythonbasicsforPHPdevelopersPage9of10However,onceyoustartlookingcloselyatanotherlanguage,youfindthatmostlanguageshavesimilartools,philosophies,andapproaches.
Learningyourfirstlanguagecanbedifficult,buttakingwhatyouknowandapplyingittoanotherlanguagecanmakethelearningexperiencealoteasier.
Evenifyoudon'treallytakeupthesecondlanguage,youincreaseyourexposuretoideasandmethodsthatwillimproveyourcraft.
Withanyluck,thisarticlehasprovidedyouwithsomeinsightintoPython.
Myhopeisthatyou'llcontinueyourlearningandkeeplookingintothisgreatlanguage.
YoumayneverleavetheworldofPHP(afterall,it'swhatprobablyputsfoodonthetable),butitneverhurtstokeeplearning.
developerWorksibm.
com/developerWorks/PythonbasicsforPHPdevelopersPage10of10RelatedtopicsVisitPythonandlearnmoreaboutthelanguage.
ReadthePythondocumentation.
TheBeginner'sGuidetoPythonagoodplacetostartlearningaboutthislanguage.
CheckoutthePythonWikiBook,whichisavailableatnocost.
Read"DiscoverPython"togetafullappreciationforPythonandwhatitcando.
PythonCookbook:CheckoutActiveStateCodetofindPythoncodesamplesthatyoucanemploy.
PHP.
netisthecentralresourceforPHPdevelopers.
Checkoutthe"RecommendedPHPreadinglist.
"BrowseallthePHPcontentondeveloperWorks.
FollowdeveloperWorksonTwitter.
ExpandyourPHPskillsbycheckingoutIBMdeveloperWorks'PHPprojectresources.
UsingadatabasewithPHPCheckouttheZendCoreforIBM,aseamless,out-of-the-box,easy-to-installPHPdevelopmentandproductionenvironmentthatsupportsIBMDB2V9.
VisitdeveloperWorksOpenandcollaboratewithsomeofIBM'sbrightestmindsinacommunitysetting.
Startdevelopingwithproducttrials,freedownloads,andIBMBluemixservices.
CopyrightIBMCorporation2010(www.
ibm.
com/legal/copytrade.
shtml)Trademarks(www.
ibm.
com/developerworks/ibm/trademarks/)

LayerStack$10.04/月(可选中国香港、日本、新加坡和洛杉矶)高性能AMD EPYC (霄龙)云服务器,

LayerStack(成立于2017年),当前正在9折促销旗下的云服务器,LayerStack的云服务器采用第 3 代 AMD EPYC™ (霄龙) 处理器,DDR4内存和企业级 PCIe Gen 4 NVMe SSD。数据中心可选中国香港、日本、新加坡和洛杉矶!其中中国香港、日本和新加坡分为国际线路和CN2线路,如果选择CN2线路,价格每月要+3.2美元,付款支持paypal,支付宝,信用卡等!...

TNAHosting($5/月)4核/12GB/500GB/15TB/芝加哥机房

TNAHosting是一家成立于2012年的国外主机商,提供VPS主机及独立服务器租用等业务,其中VPS主机基于OpenVZ和KVM架构,数据中心在美国芝加哥机房。目前,商家在LET推出芝加哥机房大硬盘高配VPS套餐,再次刷新了价格底线,基于OpenVZ架构,12GB内存,500GB大硬盘,支持月付仅5美元起。下面列出这款VPS主机配置信息。CPU:4 cores内存:12GB硬盘:500GB月流...

GigsGigsCloud 春节优惠2022 指定云服务器VPS主机85折循环优惠码

GigsGigsCloud商家在之前介绍的还是比较多的,因为之前我一直有几台机器在使用,只是最近几年网站都陆续转型删除掉不少的网站和闲置域名,包括今年也都减少网站开始转型自媒体方向。GigsGigsCloud 商家产品还是比较有特色的,有提供香港、新加坡等亚洲机房的云服务器、VPS和独立服务器等。第一、新春优惠活动优惠码:CNY2022-15OFF截止到正月初二,我们可以使用上述优惠码在购买指定G...

phpecho为你推荐
Holidaydiv大学生就业信息获取与信息分析支持ipad阿片类药物:您需要知道什么支持ipadipad连不上wifi苹果ipad突然连不上网了,是怎么回事?网络是好的,手机能上网。ipadwifiipad的wifi打不开怎么办?iphonewifi苹果wifi版和4G版是什么意思,有什么区别吗micromediaMacromedia翻译成中文是什么?google搜图google的直接搜索图片的功能为什么没了
重庆网站空间 域名服务器 长春域名注册 vps服务器租用 三级域名网站 荣耀欧洲 blackfriday 监控宝 主机屋免费空间 web服务器的架设 网站cdn加速 河南移动m值兑换 国外免费asp空间 卡巴斯基免费试用版 江苏双线服务器 域名dns 空间登入 网购分享 西安服务器托管 ssl加速 更多