the python data model - university of washington...python’s data model • everything is an object...

23
The Python Data Model UW CSE 190p Summer 2012

Upload: others

Post on 10-Jul-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: The Python Data Model - University of Washington...Python’s Data Model • Everything is an object • Each object has an identy, a type, and a value – id(obj) returns the object’s

ThePythonDataModel

UWCSE190pSummer2012

Page 2: The Python Data Model - University of Washington...Python’s Data Model • Everything is an object • Each object has an identy, a type, and a value – id(obj) returns the object’s

>>> conjugations = { “see”:[“saw”, “sees”], “walk”:[”walked”, “walks”] “do”:[”did”, “does”] “be”:[“was”, “is”] } >>> conjugations[“see”] ??? >>> conjugations[“walk”][1] ??? >>> conjugations[“walk”][1][0] ??? >>> [word[0] for word in conjugations[“be”]] ??? >>> [pair for pair in conjugations.items()][0] ??? >>> [(pair[0][0], pair[1][0][0]) for pair in conjugations.items()][1] ??? >>> {pair[0]:pair[1] for pair in conjugations.items()} ???

Page 3: The Python Data Model - University of Washington...Python’s Data Model • Everything is an object • Each object has an identy, a type, and a value – id(obj) returns the object’s

>>> def double(x): ... print “double:”, x + x ... >>> print double(2) ???

Page 4: The Python Data Model - University of Washington...Python’s Data Model • Everything is an object • Each object has an identy, a type, and a value – id(obj) returns the object’s

Types:somedefini5onsandcontext•  Somehistoricallanguageswereuntyped

–  Youcould,say,divideastringbyanumber,andtheprogramwouldconAnue.–  TheresultwassAllnonsense,ofcourse,andprogrambehaviorwascompletely

undefined.–  Thiswasconsideredunacceptable

•  Modernlanguagesmaybesta+clytypedordynamicallytyped–  “staAclytyped”meansthattypesareassignedbeforetheprogramisexecuted–  “dynamicallytyped”meansthattypesareassigned(andtypeerrorscaught)at

runAme•  Modernlanguagesmaybestronglytypedorweaklytyped

–  Forourpurposes,“weaklytyped”meansthelanguagesupportsasignificantnumberofimplicittypeconversions.•  Forexample,(5+“3”)couldtriggeraconversionfrom“3”to3

•  Forourpurposes,Pythoncanbeconsidered–  stronglytyped–  dynamicallytyped

Page 5: The Python Data Model - University of Washington...Python’s Data Model • Everything is an object • Each object has an identy, a type, and a value – id(obj) returns the object’s

GuesstheTypes

def mbar_to_mmHg(pressure): return pressure * 0.75006

Page 6: The Python Data Model - University of Washington...Python’s Data Model • Everything is an object • Each object has an identy, a type, and a value – id(obj) returns the object’s

GuesstheTypes

def abs(x): if val < 0: return -1 * val else: return 1 * val

Page 7: The Python Data Model - University of Washington...Python’s Data Model • Everything is an object • Each object has an identy, a type, and a value – id(obj) returns the object’s

GuesstheTypes

def debug(x): print x

Page 8: The Python Data Model - University of Washington...Python’s Data Model • Everything is an object • Each object has an identy, a type, and a value – id(obj) returns the object’s

GuesstheType

def index(value, somelist): i = 0 for c in somelist: if c == value: return i i = i + 1

Page 9: The Python Data Model - University of Washington...Python’s Data Model • Everything is an object • Each object has an identy, a type, and a value – id(obj) returns the object’s

DuckTyping

“Ifitwalkslikeaduckandittalkslikeaduck,thenitmustbeaduck.”

(Note:thisanalogycanbemisleading!)AtrunAme,theoperandsarecheckedtomakesuretheysupporttherequestedoperaAon.

>>> 3 + “3” >>> for i in 5: ... print i

Page 10: The Python Data Model - University of Washington...Python’s Data Model • Everything is an object • Each object has an identy, a type, and a value – id(obj) returns the object’s

Takeaway

•  ThinkabouttypeswhendesigningfuncAons,whendebugging,whenreadingcode,whenwriAngcode….alltheAme.

•  Askyourself“WhatoperaAonsarebeingappliedtothisvariable?”and“Whatvaluesmaythisvariablehold?”–  Alist,orjustanythingcompaAblewithaforloop?–  Aninteger,oranythingthatcanbemulApliedbyaninteger?

Page 11: The Python Data Model - University of Washington...Python’s Data Model • Everything is an object • Each object has an identy, a type, and a value – id(obj) returns the object’s

MutableandImmutableTypes>>> def increment(uniquewords, word): ... “““increment the count for word””” ... uniquewords[word] = uniquewords.setdefault(word, 1) + 1 >>> mywords = dict() >>> increment(mywords, “school”) >>> print mywords {'school': 2} >>> def increment(value): ... “““increment the value???””” ... value = value + 1 >>> myval = 5 >>> increment(myval) >>> print myval 5

Page 12: The Python Data Model - University of Washington...Python’s Data Model • Everything is an object • Each object has an identy, a type, and a value – id(obj) returns the object’s

What’sgoingon?Python’sDataModel

•  Everythingisanobject•  Eachobjecthasaniden+ty,atype,andavalue–  id(obj)returnstheobject’sidenAty–  type(obj)returnstheobject’stype

Page 13: The Python Data Model - University of Washington...Python’s Data Model • Everything is an object • Each object has an identy, a type, and a value – id(obj) returns the object’s

Iden5ty

•  TheidenAtyofanobjectcanneverchange–  (Currently)implementedastheobject’saddressinmemory.

– YoucanchecktoseeiftwoobjectsareidenAcalwiththekeywordis

Page 14: The Python Data Model - University of Washington...Python’s Data Model • Everything is an object • Each object has an identy, a type, and a value – id(obj) returns the object’s

Iden5ty

>>> A = [1] >>> B = [1] >>> A == B True >>> A is B False >>> C = A >>> A is C ????

>>> A = [1] >>> B = [1] >>> A == B True >>> A is B False

Page 15: The Python Data Model - University of Washington...Python’s Data Model • Everything is an object • Each object has an identy, a type, and a value – id(obj) returns the object’s

Type

•  Thetypeofanobjectcannotchange•  Itspecifiestwothings:– whatoperaAonsareallowed–  thesetofvaluestheobjectcanhold

Page 16: The Python Data Model - University of Washington...Python’s Data Model • Everything is an object • Each object has an identy, a type, and a value – id(obj) returns the object’s

BacktotheDataModel

•  Everythingisanobject•  Eachobjecthasaniden+ty,atype,andavalue–  id(obj)returnstheobject’sidenAty–  type(obj)returnstheobject’stype

•  Anobject’sidenAtycanneverchange•  Anobject’stypecanneverchange•  Anobject’svaluecanneverchange,unlessithasamutabletype

Page 17: The Python Data Model - University of Washington...Python’s Data Model • Everything is an object • Each object has an identy, a type, and a value – id(obj) returns the object’s

Example:Tuplesvs.Listsdef updaterecord(record, position, value): “““change the value at the given position””” record[position] = value mylist = [1,2,3] mytuple = (1,2,3) updaterecord(mylist, 1, 10) print mylist updaterecord(mytuple, 1, 10) print mytuple

Page 18: The Python Data Model - University of Washington...Python’s Data Model • Everything is an object • Each object has an identy, a type, and a value – id(obj) returns the object’s

Whydidtheydothis?>>> citytuple = (“Atlanta”, “GA”) >>> type(citytuple) <type 'tuple’> >>> citylist = [“Atlanta”, “GA”] <type ’list'> >>> weather[citytuple] = “super hot” >>> weather[citylist] = “super hot” Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list'

Page 19: The Python Data Model - University of Washington...Python’s Data Model • Everything is an object • Each object has an identy, a type, and a value – id(obj) returns the object’s

Whatwouldthismean?

>>> citylist = [“Atlanta”, “GA”] >>> weather[citylist] = “super hot” >>> citylist[1] = “Georgia” >>> weather[[“Atlanta”, “GA”]] ???

Page 20: The Python Data Model - University of Washington...Python’s Data Model • Everything is an object • Each object has an identy, a type, and a value – id(obj) returns the object’s

MutableandImmutableTypes

•  Immutable– numbers,strings,tuples

•  Mutable–  listsanddicAonaries

Note:asetismutable,butafrozensetisimmutable

Page 21: The Python Data Model - University of Washington...Python’s Data Model • Everything is an object • Each object has an identy, a type, and a value – id(obj) returns the object’s

ComprehensionExamplenames = [“John von Neumann”, “Grace Hopper”, “Alan Turing”, “Charles Babbage”, “Ada Lovelace”] split_names = [name.split(“ “) for name in names] last_names = [split_name[1] for split_name in split_names] last_name_first = [sn[1] + “, “ + sn[0] for sn in split_names]

Page 22: The Python Data Model - University of Washington...Python’s Data Model • Everything is an object • Each object has an identy, a type, and a value – id(obj) returns the object’s

Digression:MorewithComprehensions

[(x,y) for x in org1 for y in org2 if sim(x,y) > threshold]

YouaregivenafuncAondefsim(sequence1,sequence2)“””ReturnanumberrepresenAngthesimilarityscorebetweenthetwoarguments“””…

Youaregiventwolistsofsequences

org1 = [“ACGTTTCA”, “AGGCCTTA”, “AAAACCTG”] org2 = [“AGCTTTGA”, “GCCGGAAT”, “GCTACTGA”]

Youwanttofindallpairsofsimilarsequences:similarity(A,B)>threshold

Page 23: The Python Data Model - University of Washington...Python’s Data Model • Everything is an object • Each object has an identy, a type, and a value – id(obj) returns the object’s

Evalua5ngComprehensions

somethingthatcanbeiterated

anexpression zeroormoreifclauses

forclause(required)assignsvaluetothevariablex

[(x,y) for x in org1 for y in org2 if sim(x,y) > threshold]

zeroormoreadiAonalforclauses