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/)

RAKsmartCloud服务器,可自定义配置月$7.59

RAKsmart商家一直以来在独立服务器、站群服务器和G口和10G口大端口流量服务器上下功夫比较大,但是在VPS主机业务上仅仅是顺带,尤其是我们看到大部分主流商家都做云服务器,而RAKsmart商家终于开始做云服务器,这次试探性的新增美国硅谷机房一个方案。月付7.59美元起,支持自定义配置,KVM虚拟化,美国硅谷机房,VPC网络/经典网络,大陆优化/精品网线路,支持Linux或者Windows操作...

wordpress专业外贸建站主题 WordPress专业外贸企业网站搭建模版

WordPress专业外贸企业网站搭建模版,特色专业外贸企业风格 + 自适应网站开发设计 通用流行的外贸企业网站模块 + 更好的SEO搜索优化和收录 自定义多模块的产品展示功能 + 高效实用的后台自定义模块设置!采用标准的HTML5+CSS3语言开发,兼容当下的各种主流浏览器: IE 6+(以及类似360、遨游等基于IE内核的)、Firefox、Google Chrome、Safari、Opera...

宝塔面板企业版和专业版618年中活动 永久授权仅1888元+

我们一般的站长或者企业服务器配置WEB环境会用到免费版本的宝塔面板。但是如果我们需要较多的付费插件扩展,或者是有需要企业功能应用的,短期来说我们可能选择按件按月付费的比较好,但是如果我们长期使用的话,有些网友认为选择宝塔面板企业版或者专业版是比较划算的。这样在年中大促618的时候,我们也可以看到宝塔面板也有发布促销活动。企业版年付899元,专业版永久授权1888元起步。对于有需要的网友来说,还是值...

phpecho为你推荐
深圳市富满电子集团股份有限公司可現場列印的全自動單面和雙面印相機usergoogle支持ipadphotoshop技术ps是一种什么技术??????ipadwifiIpad怎么用移动无线上网fusionchartsFusionCharts连接数据库你是怎么解决的,能告诉我吗?谢谢啦ms17-010win1038度古贝春珍藏10价格?联通版iphone4s苹果4s怎么分移动版联通版电信版?联通版iphone4s苹果4S移动版和联通版有什么不同
重庆服务器租用 泛域名解析 淘宝抢红包攻略 阿里云邮箱登陆首页 精品网 360抢票助手 css样式大全 北京双线机房 网站木马检测工具 泉州电信 129邮箱 网络空间租赁 福建铁通 主机管理系统 全能空间 ncp forwarder cdn加速技术 美国服务器 西安电信测速网 更多