Sowhatwe'retalkingabouttoday, Todaythetopicisgoingtobeobjectorientedprogramming, whichis a programmingparadigmthatyou'llfindin a numberofdifferentlanguagestoday.
Inparticular, we'regonnabelooking a python, thoughthere's objectorientedprogramminginlanguageslikeJava, forinstance, andmanyotherlanguagesaswellarebeginningtousethisparadigm, andit's quitepopularintheprogrammingworld.
A shoppingitem, forinstance, mightbesomecodesomeactionthat's associatedwiththatparticularobjectthatyoucanusetomakesomethinghappen.
Kindoftakingitabovethesortofbaremetalofthecomputer a littlebitmorethansomethinglikeSeewhereyou'reliterallycodinginstructionsthatkindofroughlymappedouttheCPUtalksininnocence.
Yeah, exactly.
It's often a featureofhigherlevelprogramminglanguagesthatallowyoutoreason a littlebitmoreabstractlyyoutoorganizecodeinparticularways.
AndiInthispythoninterpreter, I canbegintotypevalleythenamesofexpressionsorvalues, and I canseewhatthey'reequalto.
Sothenumber I typedinthenumber 50 forinstance, andwhat I getbackfromtheInterpreterisOK.
Thisisthevalue 50 on.
Ofcourse.
That's obvious, cause I typedinthenumber 50 exactly, butyoucantypemorecomplexexpressions, right?
I couldtypeanexpressionlike 20 pluseight, andwhen I getbackisnotliterally 20 pluseight.
But I getthatexpressionwhichgetthevalueinitto a value.
Andthatvalueinthiscaseis 20 forinstance.
Andsothis 28 hereit's a numberinparticular, it's aninteger, andif I typeinthenumber 28 okay, itsvalueis 28.
Butthere's a specialfunctioninpythoncalledtype, which I canuseif I saytype 28 forinstance, I canseeallright, whatistypeAndhereweseethefirstinstanceofanobjectorientedprogrammingwordthiswordclassclassisgoingtotellme, sortofWhattypeofinformationisthisvalue?
Thenumber 28 it's tellingme, belongsto a classcalledint.
Andsothewaytothinkaboutthisis 28 isanobject.
Itis a thingthatexistsis a valueinpython, anditbelongsto a class.
Whattypeofthingis 28 28 inthiscaseisanend, andithappenstobeoneofthebuiltinclassesinpythonthat I canuse.
Andinfact, anytimeyouuseanintegerandpythonyou'reusing, anobjectthatisofthisintoclassthrivesonbeingmoreof a dynamiclanguage.
Itonlyworksbecausethisvariable X iswhatwemightcallaninstanceoftheclass, andwhen I sayinstance, I justmeanthatifitis a classthananytime I haveanobjectthatbelongstothatclassthat's goingtobeaninstanceoftheclass.
So X, inthiscaseisaninstanceofthisintoclass.
So, likeclassbeingtheblueprintandthenactual 28 isthephysicalthing.
Startifwewanttotakeit, Youknow, into a physicalanalogy, thephysicalthingweusetheblueprinttocreateorconstructexactly.
Butwhat I thoughtwedotodayisshowyouhowyoucanusingthesyntaxofobjectorintoprogrammingandJavaorpythonrathercreateyourownclassesthathavetheirowndatathatbehaveintheirownparticularwaysbecausethereare a lotofbuiltinclassesandpython.
SoistheabilitytodoliveGoogleDocstylecollaborationon a textfile.
Butif I'm onAdamand I wanttocollaborateon a pieceofcodewithmypartner, I cansignwithmygethaveusernameandmypartnerconsigninwithhisorhergethubusername, andwecanjustbeworkingonthesamefile, typinglive, seeingeachother's changesatthesametime.
That I think, is a verycompellingfeatureofAdam.
It's veryusefulforparaprogrammingforworkingcollaboratively, but I haven't reallyseenanyonequitebeabletoreplicateinanythinglikethat.
Allofthebigtechcenter, justnowadays, V s codesublimetextAdamandmanyothershavesomanythirdpartypackagesthatyoucaninstallthathad a varietyofdifferentfeaturestotheapplication.
Uh, what I'lldohereiswhat I thoughtwedoiscreate a classthat's goingtorepresent, like a book, forinstance, a bookthathas a titleandauthor, forinstance, andmaybeotherdataassociatedwithitaswell.
So I'm gonnagoaheadandsavethisinsideof a filethat I'llcallbookeduppie.
Um, andwhat I'm goingtodois I'm goingtocreate a newclass.
I'm goingtobedefiningthesyntaxfor a classthatisgoingtoallowmetocreateasmanybooksas I wantbasedoffofthisclassdefinitionbasedoffthisblueprintforwhatitisthat a bookis.
Soit's a classbook, andthisismywayinPythonofdefiningsomebrandnewclass.
Andthefirstthingthat I needtodowhen I create a classisdefinesomesortoffunctionforwhatshouldhappenwhen I trytowhat's calledinStan.
Sheatethisclass.
When I trytocreate a book, whatshouldhappenandinpythonthisfunctionhas a littlebitof a crypticname.
It's calledUnderscore.
Underscore.
Initunderscoreunderscore, innit?
Standingforinitial I'veandPythonoftenmakesitspecialfunctionsorspecialmethodshavetounderscoresoneithersideofitsincejust a pythonconvention.
Andsoinitisgoingtobe a functionthat's goingtocreate a newbook.
Andwheneverwehave a particularfunctionsthataregoingtorunon, objectsonobjectsthatbelongto a classweregenerallygoingtocallthesemethodsinsteadoffunctions.
AllofthemethodsthatoperateonobjectsinPythonwillhavethisargumentcalledSelf, whichis a littlebitstrangeatfirst.
Butbasicallyselfjustrefersis a wayofnamingtheobjectthatwe'reworkingwiththatwemightbecreating 5 10 20 differentbooksandwewanttobeabletoreferencethedatainsideofeachindividualbookandselfisgoingtobe a variablethatisalwaysgoingtoreferThio, thebookthatwe'recurrentlydealingwith.
Sowhen I create a newbook, whatarethetypesofinformationthat I wanttoassociatewiththebooks?
Thisisthequestionwhen I create a book, whatgoesintothebook?
Well, probablyatminimum.
Weneed a title, forinstance, andso I'm addingthistitleargumenttotheinnitfunction.
Rememberthisinnit?
Functionisthecodethatisgoingtorunwhen I trytocreate a bookandhearingthing.
When I create a book, thebookitselfisgoingtobecalledself, but I alsowanttoprovidesomeadditionalinformation.
When I createthebook, I wanttotellthebookwhatitstitleisgoingtobe.
Okay, makessense.
Thisisgoingtotheparentheseswhenwecreate a newbookinourcode.
Exactly.
Andwe'llshowthatinjust a moment.
Andsonow, insidethecodeofthisinnitmethod.
When I create a book, I wanttostoreinsideofthebookinsideofthisselfobject, I wanttostorethetitle, andsowhat I candoisinanyobjectyoucanassignvaluestwopropertiesofthatobjectusingdotnotationinpython, where I cansayselfdotandthenthenameofsomepropertyinthisselfdotpropertynamewherepropertynamecouldbeanythingandgiveitsomevalue.
I wanttochangethenameofthepropertyinthebookcalledTitletobeequaltowhateverthistitleargumentis.
Andso a commonparadigmwhenyou'recreatingobjectsistosay, Well, let's passinthetitlewhenyoufirstcreatethebookAndthenwhatdo I dowiththattitle?
Well, I saidittobeequalto a selfducktitle.
Inotherwords, I taketheselfobject, thebookthat I'vejustcreateditmodifyitstitleattributeandsaiditequaltotheargumentthat I'vepassedit.
So a lotofsyntaxafar, someofwhichmaybe a littlebitunfamiliar, butlongstoryshort, allwe'vedonehereistofind a blueprintforhowtocreate a book.
I create a bookbyproviding a title, andthat's goingtostorethetitleinsideofthebookthedotbeingfromwiththemostthenewestthingfor a lotofpeople.
And a lotofpeoplemighthaveused a moduleinPythonareimported, youknow, partofthestandardlibraryorsomething, andusedittherebutnotactuallyseenitinthecontextofcreating a classthemselvesoryeah, yeah, yeah, inthesamewaythatwehad, like, thenumberbefore, where I wasabletosaythatnumberdotnumeratororgotdenominator, That's thesameideaofaccessing a propertyoftheobjectwheretheobjectstores a wholebunchofdataand a wholebunchofcodewithit.
Andif I wanttoaccessthedataassociatedwithanobject, I justreferenceitbythenameofthatproperty.
Selfdottitle, inthiscasemakessense.
Well, youseethere, whynotusethepropertiesliketitleinsidetheclassassignedto a variableassignedto a verythey'reprobablyreferringtowhatwouldbeecstaticvariableinthiscase, okay, Wemighttouchonthestaticvariables a littlebitlater, orpythonwillgenerallycallthemlikeclassvariables.
I guessthatwouldbe a goodpointtobringupon.
Maybethey'resaying, Whynotjustcreate a newvariableinhere?
Whydo I havetocallitselfdottitle?
Whenway?
Sure, youcouldimaginethatwecouldjustcallitvariable T centeredequalthetitle, forinstance.
Butrememberthatifyoudefine a variableinsideof a function, whenthatfunctionisdonerunning, weloseaccesstothevariablesoimmediatelyafterthisinnitfunctionhasdonerunningthisteavariableisnolongergoingtoexist.
Wecanseethatif I dosomethinglike, I'lldefine a functioncalled F, andwhateverisgoingtodoisset X equalto 10.
Forexample, if I runthefunction f andthen I say, OK, whatis X like?
I print X toseewhatisthevalueof X.
I get a nameinright X isnotdefined, eventhough I called F, whichsetthevalueof X uphereafterthefunctionwasdone, executing I lostaccesstothatVariable X becauseitsscope, sotospeak, islocaltothatparticularfunction.
Soafterthefunctionisdonerunning, I nolongerhaveaccesstothis X.
Thesamething's goingtobetrueofthisvariabletitle.
Thisisjust a variableinsideofthisfunction.
Andsoif I don't doanythingassoonasthisfunctionisdonerunning, I'm gonnaloseaccesstothatvariable.
Andso I wanttoimportfromthispipeonfilefromthismodule, thebookclass, andsothesyntaxandpythontodothatistosay, frombookThat's thenameofthemodulebookeduphighthat I wanttoimporttheclassfrom.
LetmeimportthisbookClassCapital B.
Andrightnow I'veimportedthebookclassifytypebook.
Allright, thisis a class, andit's calledBookPrince.
It's essentiallyextendedthelanguage, andin a way, wenowhavenew.
Yeah, wehaveaccessto a newclass, thenewnowthatwedidn't haveaccesstobeforebecausewe'vejustcreatedthis.
Soif I wanttocreate a newbook, I callitbeWell, say B equalsbook.
Andthentheargumenttobookisgoingtobethetitle.
Thenameofthebookthat I wanttocreateonyourfavoritebook.
Um, it's been a while.
HarryPotteragainstHarryPotter.
HarryPotter.
Uh, well, dioonthesourceofstone.
Whichonewasyourfavoritepartof a favoriteHarryPotterbook?
Thattough?
Itis a toughone.
I wasquite a fanofthefourthbook, TheGobletofFire.
I thoughtwasverybutthey'reallThey'reallquiteexcellent.
Sowerecommendthemgiven.
Allright, So I'm creating a newbookandintheparentheses.
Yeah, providingisanargumenttobookthetitleofthebookthat I wanttocreate.
And I'm savingthatbookinsideof a variablecalled B oppressor, turnandright I'vecreatedthisvariablecalled B B is a bookobjectandinparticular, if I sayWhatisthetypeof B?
What I getisallright.
B is a book, andinparticular I cannoaccessthepropertiesofthisbook.
If I wanttogetthetitleofthebook, I cansaybedottitle, forinstance.
Sothisis a distinctionbetweenpythonandlanguageslikeJava, forinstance, whereinJavayougettohave a lotmorecontroloverwhattypesofthingsthey'republicandwhattypesofthingstheprivatenoticethatthereisnonotionoflikeaddingpublicorprivatetothevariableshereandpipeonjust a bitof a differencebetweentheattributesthatwedefineinpythonandinJavaandsothetypesofthingsthatyoucandowithclassofendupbeing a littlebitdifferentas a result, AretheresomeconventionsMaybethatwecouldusetokindofsimulateprivatevariablesandfunctions?
Yeah, a commonconventioninPythonisifinafterPetestartswithanunderscore, thoseattributesshouldbeconsideredprivate.
Itdoesn't have, I guess, maybe a morefistbehavior, ourofficepolymorphicbehavior, dependingonthedatatime.
Butitmaymayactuallywin a casethatpythonspecialcaseslikeinterferencestuffsothatyoucanusethemasbecauseit's partofthegrammarforthelanguagelikenumber.
SowhatdoyoumeanyouSoyouwon't beable, Thio.
Ifyoutryandadd a bookThio a number, forinstance, that's notgoingtoworklikeyoucouldn't youcouldn't theoreticallydefineyourownclassthatworkslike a numberbecausepythonspecialcasesyoumightbeabletoSoyoucanthereotherpropertiesthatyoucanadditto.
Thistheseclassesthatallowyoutogetittobehaveinparticularwaysoflikecomparingwhether a thingislessthananother, changingthewaythatitrespondstoparticularoperatorssothatwecanget a lotmoresophisticatedthanwe'vegottensofarintermsofthelexicalParsing, though, likethefactthatyoucanuselike 23 as a literalOh, the 23 literalyeah, that's specificallycreatesanintoobject.
Andthat's I imaginethat's probablysomethingthat I don't knowifwecouldgetthatkindofflexible, flexiblebehavior, especiallywecouldlexical e specialcaseinnewdata.
Yeah, asfaras I know, thereisnowaytodothatinPython.
Soifsomeoneknowstheway, so I think I thinkthat's probablywhatthey'rereferringtoit.
Butif I interpretedthatincorrectly, pleaseletmeknow.
Andif I changedthetitletobelike a floatingpointnumberyoulike, eventhoughitdoesn't reallymakesensetodothat, youcoulddoit.
Therearewaysoftryingtoprotectagainstthis.
Youcanaddsomespecialcodetoyourclassesandsaywhen I trytosetthevalueofherproperty.
Youshouldrunthiscodethatmaybeaddsometypecheckingofyourowntomakesurethatitisinfact, a string.
Butthoseairfeaturesareavailable, butnotpartofthemostsimplisticwaythatwecouldcreate a classinpython.
Andsooneofthethingsyou'llnoticeaboutPythonasittriestomakethesyntaxforcreating a newclass, creating a newobjectassimpleaspossible, suchthatforthevastmajorityofcases, youcanstickwiththesimplestintax.
Yeah, sothegeneralwayyoudosomethinglikethatinPythonisif I wantedtosayallowformetocreate a bookthat I thetitle.
Butmaybe I alsowanttobeallow a booktohaveanauthoraswell, so I canaddanauthorargumenttotheunitfunctionandthensay, likeselfdotauthorequalsauthor.
Andnow, if I goaheadandreimportfrombookimportbook, when I create a newbook, Be I'm goingtoneedtosayThisbookiswith a HarryPotterandit's by J.
K Rollingafterspecifiedbothargumentstobeabletocreate a book.
Andif I hadonlyprovidedoneargument, justHarryPotter, well, then I wouldhavegotten a typeairbecauseinitwasmissingonerequiredpositionalargument.
It's missingtheauthorargument, inotherwords, tocreate a book I needtoprovideanauthor, but I didn't.
Butsomelanguages, likeJava, anythingotherobjectduringtwoprogramminglanguageswillallowyouhavedifferentconstructors, wheresometimesyouwanttobeabletoonlyprovide a titleandnotanauthor, andsometimesyouhaveboththetitleandanauthor, forinstance, andsowhatyoucoulddothatPythonisbygivingthesearguments, defaultvalueswerebackinside.
Authorbydefaultisgonnabenoneasinhasnoauthor.
Andsonowif I sayfrombookinPortBook, letmesayBeoneisgoingtobe a bookcalledHarryPotter, whoseauthoris J.
K rollingonDhe.
Letmemoveittothissidesince I coveredup, Um, beonehas a titleandtheonehasanauthor.
Butif I canalsotofind a bookbetoo, thatisjustHarryPotterleavingofftheauthorargumentnoticednoerrorthistimebecauseif I didn't provide a valueforwhatauthorisequaltoitsjustgoingtousethatdefaultvalueofnone.
So B two's titlenowisstillHarryPotter.
Butif I tryandget a B two's author, thereisnoBut I justalwaysassumedtheothers J k rollingforeverybook.
Oryoucoulddothat.
Youcouldgiveit a defaultoutthere J k rollingforeverything.
Certainlyifyouwanttodoallright, I don't wanttogetusThiotaketoolong.
Inthatcase, what I'd liketodois I wouldliketobeableThio, addsomecodethiothisparticularbook.
I'd likethebooktobeabletodosomething, andsowhat I'm goingtodois I'm goingtoadd a specialmethodcalledprintinfoandprintInfoisgoingtobe a functionthat I canuseon a bookthatprintsoutinformationaboutthebook.
Rememberthatobjectsandtheobjectorientedprogrammingfenceare a combinationofdataandcodedata.
Hasanyinformationassociatedwiththeobjectandthecodearegoingtobethesemethods, thesefunctionsthatworkonobjectsthatcoulddosomethingwiththeobjectAndonething I mightliketodo.
It's printoutinformationaboutthebook, so I'm goingtofind a functioncalledprintinfothattakesselfagainasitsargumentselfisgoingtobethisimplicitargument.
It's alwaysgoingtobeprovidedwheneverwe'recalling a methodonanobject, andthatallowsmetoaccessthepropertiesofthatobject.
Soif I wanttoprintoutuh, thebook's title, I canprintitselftitle.
Butifyouwantedto, youcould, uh, talkin F atthebeginningofthestrangetosay, thisisgonnabe a formattedstringandthenusecurlybracestopluginvalues.
For I couldsayselfdottitleiswrittenbyselfdotauthor, forinstance, andthat's gonnahavetheexactsamebehaviormayactuallybe a littlebitmoreefficientinthiscase.
Seeifyoucanwrite a pythonprogramthatgetsyoutheanswertothatquestion, andthenyoucanplugitintothewebsiteandseeiftheansweriscorrect.
Soalltheproblemsresemblesomethinglikethis.
Theyintroducesomeproblems.
I askyou a question, andusuallythewaytosolveitisgoingtobetowritesomeprogramtobeabletodoit, andaddedBrowniepointsifyoucancomeupwithanefficientsolutiontotheproblem, tryingtofigureouthowtogetittorunveryquickly.
But I foundtheusedtobetheleastinterestingproblemsthatofteninvolvedwithbunchofdifferenttypesofprograms.
Youhavetowrite a bunchofdifferentideas.
Haveyoudoneall 700?
I havenotdoneall 700 done.
Veryfewoftheseactuallydone.
A coupleofthem, um, beautifulyounggentlemanasked, Canyouavoidhavingtogivedefaultvaluesusing a hashoranarrayas a parameter?
Using a hashornocashtableisprobablythemeanusingeitherhashtableordictionaryorderRay, aspromotedto a function, canyouavoidhavingtogiveexplicitdefaultvalues?
Uh, inthecaseof a pythonfunction.
Yourchoicesareeithergivetheargument a defaultvalueorwhenyoucallthefunctiontoprovide a valuewhenyoucallthefunctionsowedon't need a defaultvalueonauthor.
Butinthatcase, nowyou'regoingtoneedtotellmewhotheauthoriswhen I trytocreate a book, thenwealsobealludingto K areeggsorkeywordare?
If I callthefunctionpassingin a equalsthreeandlikebeequalsfour, forinstance, what I getisalright.
A dictionarythathas a equaltothreeandvehiclebeforeButif I have a dictionaryalreadycalled X, where a issaidtothreeandbeacceptedforif I trytocall F with X, thatdoesn't quitework.
But I thinkifyoudo f staracts, thatmeanstakethedictionaryand, like, splititscomponentsupintovariousdifferentparts.
Andsoimperativeprogrammingmakessenseis a stylethereandthenfunctionalprogramming, whichwhichwasbroughtupwell, it's anentirelydifferentparadigmofprogramming, whichisalsoveryinteresting, perhapsworthyof a topic.
Andthere's a lotofveryinterestingapplicationsoffunctionalprogrammingthatgivesyouaccesstosomenicerecursivetoolistheabilitytowrite a lotofprogramsin a veryelegantway, andsothere's a lotthereaswellonebigsortofthingthatpeoplecouldtakeaboutobjectsintheprogrammingestate, forexample, being a thingthat's verymonolithicandhardtomanageforreallybigapplicationsandfunctionalprogrammingtriestoeliminatethatrightfunctionalprogramming.
Ingeneral, a purefunctionis a functionthathasnosideeffectssuchthatnomatterwhatdidn't putyouprovidedtothefunction, it's alwaysgoingtoprovideyouwiththesameoutput, nomatterwhat.
If I wanttorepresentit, infiniteamountofdata, imperativeprogramminglanguagecouldneverbeabletodosomethinglikethatbecauseourcomputerphysicallycan't storeaninfiniteamountofdata, butwithlazyevaluation.
We'vegot a bookclass, andmaybe I wantedtofind a classthat's goingtousethisbookclass, maybetofind a classforwhat I mightwanttousethisbookdatasomewhere, maybeinsideoflike, a library, forinstance, wherewehaveaninventoryofbooksandwe'rebookscouldbecheckedoutorreturnedforinstance.
Soletmegoaheadandcreate a newfilecalledlibrarydotPie, and I'm gonnacreate a newclasscalledLibrary.
And I'm gonnadefineaninitialeither a constructorfunctionandthisconstructorfunction.
Rightnow I'm justgoingtostorelike a listofbooks.
What a libraryhaswithinitis a wholebunchofbooks.
Andsowe'regoingtosayselfdotbooks.
And I'm justgonnabydefault, SenateequaltotheemptylistWhen I firstcreate a library, therearenobooksthatareinsideofthatlibrarybydefaults.
I'm definingwhat a libraryiscreating a blueprintfor a librarywhereright, Bywhereby.
Whenever I create a library, I'm goingtoinitializeitwithanemptysetofbooks.
Andnowwhat I wanttodoisaddsomecodetothislibrarysomeoperationsthat I mightwanttoperformonthislibrary, forinstance, I mightwanttoadd a booktothelibraryat a bookjustcalledbook, forinstance.