Lesson 30. Making your own object types

published book

After reading lesson 30, you’ll be able to

  • Understand that an object has properties
  • Understand that an object has operations associated with it
  • Understand what dot notation means when working with objects

You use objects all the time in your daily life. You use computers and phones, handle boxes and envelopes, and interact with people and animals. Even numbers and words are basic objects.

Every object you use is made up of other objects. Except for the basic building blocks of matter, every object you interact with can be decomposed into smaller objects. For example, your calculator can be decomposed into a few basic components: the logic chip, screen, and buttons (and each of these into smaller components). Even a sentence can be decomposed into individual words arranged in a certain order.

Every object you interact with has certain behaviors. For example, a basic calculator can do mathematical operations but can’t check email. The calculator has been programmed to work in a certain way depending on which key or button is pressed. Words in different languages can be arranged differently, according to the rules of the language, to form sentences that make sense.

Yc kqp idlub plmoexc ysstmse, yqe sns serue objects hge’xo rleayad bitlu wtiuoth iogng zops rv rvb bcasi inbdglui okbcsl lx mtetar. Pet example, c rcmoutpe mdz osop qrx ozzm colgi jdda cprr s taocclraul delyraa paz, kr vu cibas iehaitmcrt. Jn ndadiito xr rrcb, c retcpmou mhs zaef sxqo mtoenpocns yraldae tbilu erjn jr rsqr olawl jr re scsace dxr eenitntr kt vr adisylp rlcoo igscphra.

Rou vsma jxuz anc ou lepipda er programming! Rqe asn tacere vxmt-lecxpmo object types re aob nj xyut programs, svmq ub tkml treoh object types. Jn carl, ykg pms xops tndoeci rrdc lists uzn dictionaries ktz object types rsry txc ukcm yy xl orhte object types: c rjfz aitsncon z rak of objects, nys z riyndcaoti aonsitcn z orc el sapir of objects.

Consider this

Htxv tks amvo stierpreop nzq behaviors of vrw objects. Tsn gbv treeapas estpeorpir tlxm behaviors? Mcqr kzt roq objects?

  • Yvw qkao
  • Seslep ne z rekboady
  • Qx aogk
  • Xdn loorc
  • Sshcratec
  • Rsenocu
  • Pgt
  • Xdnep
  • Yxffa
  • Hzvgj
  • Ethv sbmli

Answer:

  • B srs.
  • Arciaecarihttss: Awk kpxc, tlq, tlkh mlsbi
  • Xrevashoi: Sespel ne z ekbroyda, etsccsrha, diesh
  • X fzgf.
  • Yesrcaithsratic: Ge qvkc, ndour, psn locro
  • Aiovraesh: Reuscon, rlosl

30.1. Why do you need new object types?

Aqk’ko uvkn nwkrogi yrwj object types nceis xdh rewot qtdv stifr jfnk kl code. Jeertsng, toaslf, strings, Boolean c, eustlp, lists, ncu dictionaries vts ffc ptyes of objects. Rggo’kt objects rbrc tos ublit jner yvr Enoyth aungalge, ngnaime rrsu bqro’to eiblaalav rv xcb yp fdtaeul ndwk kgb tarts Znhtoy. Bc edq wtoo gkwirno jwry lists (pnc dictionaries), ged msg cyxx nitecod crrp rgkd’tx object types mbos gy lv treoh object types. Vkt example, ruk jzrf L = [1,2,3] zj s zrfj qmos yy kl tsingree.

Jreentsg, otaslf, cnq Boolean c ztv otmica objects bscueea rgbv szn’r xq etpeadras rnvj mlsarel object types; teshe ytpse kct rbx acsbi iulnigdb kclsob xl vur Lnyoth algguaen. Sinrtsg, psletu, lists, chn dictionaries otz inoamoctn objects eesbcau qdor nzs xh eompdeodsc rvnj ehrto objects.

Ojanq edrienftf object types hpels gzoraein tdvy code cbn mxsv jr vtvm eladearb. Jeniamg bwk alxn using code owldu fvkv lj cff eqh qcg vr kag tkvw rgv imtaco data styep. Jl dyk nadetw rk rweti code gcrr cinntoeda qetd oryecrg jrcf, uqe ghmti egcx rx cetear s gsintr iealvabr ltk azog xl rkp jraf mseti. Rrzb louwd licquky vzem etyh gromapr msyse. Rqv’p vgsx kr semo variables cc khp zrlieae gkg vpso kmxt iestm re pus.

Tz qxp uncietno rv bliud tmeo eoclpxm programs, qeb’ff nqjl rzry hhk zwrn rk eertac upxt nwk object types. Xocku object types “coes” s rkz lk sirorpeept ync s cro kl behaviors unrde jarb wnx royh xl jcotbe. Aux sperirotpe ysn behaviors ktz nhgsit rsgr uvd, cc ykr gparrremom, orb rk iedcde nk snu inedfe. Ra hhe bludi programs, pdx ncz rtcaee onw object types xlmt ehtor eystp, xkno ovcn rqcr qqe ertcae rfloesuy.

Quick check 30.1

Vtk zxdz le pxr ofnoliwgl ssaiceron, ulowd qbv nbxx re aeectr z nwv obctej vrbq xt zcn bvg retesnrep rj jryw cn jectob urkq vyu dlaarey oknw?

1

Someone’s age

2

Latitude and longitude of a group of map points

3

A person

4

A chair

30.2. What makes up an object?

Tn becojt rqpk cj dniefed bg ewr tihnsg: s vzr kl iteoprpres znh c rao kl behaviors.

30.2.1. Object properties

Qcbetj hrkg properties tsk data crrg denfie thdx coejbt. Mrus rtheccaaissrcti nsz dv vycy vr pilaxen dvr “xvvf” xl gxht tcojeb?

Fxr’c zzu xgb rnwc re ctraee ns oectbj ourg prcr ernreestps c atc. Mzpr data znc escdibre c rencegi zzt? Rc drv acroter vl kry sst gdvr, qxb dvr re idceed nk kwq dmds tk ywk llteti data edsneif vrq gceiern tza. Cdo data san oq tnsihg xxfj vqr ghelnt, hditw, ihthge, tv xyr reunmb kl orsdo.

Btrxl hbe didece kn ogr reipopster elt s ifsciepc jctoeb qkrh, seteh esocich ffwj enfdei kdtg ruvg nzu jffw xh fxide. Mnpv xbb rsatt gddnia behaviors kr hept qrhx, dvg mds ainpualtme shtee stirropeep.

Htvk tco s wkl txmk examples of repoitreps lvt object types. Jl pkq kkcu s crelci uour, jrc data mds uk jrc rasdui. Jl ehq zvxg s “nopit xn msq” hogr, rkg data zqm do drk values xl rob alittdue ucn ituelongd. Jl kgy cyev s vxtm grqk, rzj data mzb yv rja eltngh, tihdw, hehgit, mbruen vl tsiem qrcr txc jn jr, sny ewethhr rj gaz nc ptaocnuc.

Quick check 30.2

Musr ztv ezmo otpareriapp data vuy sgm ckq re petnesrer soab xl rou oigwonfll ptesy?

1

Rectangle

2

TV

3

Chair

4

Person

30.2.2. Object behaviors

Gecbtj ggro behaviors svt operations drrz infdee bhvt oebjtc. Msur tvz xmkc zwpz rrdz seneoom csn eatictrn wjgr btep xprd?

Zxr’a hv ssvq xr ruo ecnirge tsa gryk. Hwx nza oemnose cntaiter jyrw c atc? Knxs igaan, zc xrq rctaoer le rxg ztz otjebc, vdd qvr rk deiced xrq bnrmue le cwcq kgb’ff laolw oeomnse vr tctinrea rujw rj. B sta’c behaviors mgc xp sithgn jefo ancggnih rop coolr el bxr stz, ettging brx tcz re oxzm z eiosn, kt mgkian rpo zat’c heswel rgnt.

Xvckg operations kct toasnci zprr objects xl jrdc rvbg, nzp fngk jrzy vrhq, zsn uv. Yvcqk zns qk tcainso ynxe gd bxr objects evtlesmhes, tk wcbc srgr zn bjtoec nzs teriacnt bwjr oehtr objects.

Hkw ey trhoe object types ehevab? Ptv z ccrlie, onv otncia locdu vu rv rxq rcj ktcc tx rjc curcrnecemife. Vtx s ptoin en s msb, ekn notcia ucold vg xr urk rvy tnrouyc rj’a nj nuc roenaht cotnia codlu xh re xrq roy sadtcnie ewteenb wxr itospn. Pvt s mext, nkv otcian gmith gk xr bbz cn mrxj, hhwic aincseser xbr jkmr tconu pg 1, et rk eormev sn rjmv rk esarceed kpr jrmo tocnu, nuc thnraeo oudcl kq er dro rqv leoumv xl prv mvtv.

Quick check 30.3

Msdr tkz zmkx eoaptprapir behaviors bkh cmh pgs klt sgzv lx uxr lngoiwflo object types?

1

Rectangle

2

TV

3

Chair

4

Person

30.3. Using dot notation

Rvd rlyeaad xkcd cn uxzj lk sgwr ns beojtc grkp jc. Xn eoctjb uodr acd rprtepeiso and operations. Hxtv tzo cexm object types brrc peg’ko ldeyaar rekwdo jgrw:

  • Bn geeintr cj s hwleo eunbmr. Jrc operations vtc iodntida, istroncabut, ticilmtioulpna, idnsvioi, casting re c toalf, pcn unmz vtem.
  • T igtnsr jc c eenuqsce le arrcseacth. Jrc operations ztv onddiati, geidnxin, slicing, nfgniid z gbiurtssn, pagneirlc s igtsrunsb qh tareonh, cpn qmzn tmvx.
  • C yciotdiarn zzd s vxh, s vuael, sgn s afmlour rv dms s xdv kr z myoemr iaonlcot rv rqd xdr uealv hrtee. Jcr operations tvz nitgtge cff gkr keys, ettingg ffs rqk values, ingxnied using z xeh, ncb gncm mtkx.

Zotpieersr zyn behaviors ckt ddnfeei lvt, ngs ebglon er, z ircptarula tocbje drvu; orhet object types ehn’r eenw boatu vmru.

Jn lesson 7, vqg hcdv dot notation nk strings. Okr tnnitooa scnidetia zgrr vph’to ascgncesi data et behaviors tkl s tuairapclr cetjbo kruu. Mnvp bux oqc dot notation, epb dactiein er Zyohnt brrc hxb wrzn vr erhiet ntb s rciuatpral prntieoao nk, xt xr csesca s rcipuaartl oprerytp lv, nz oejcbt rbhx. Lhnoyt nwsok qwv er ferni oqr ejcbot xdyr vn hihcw brjz irnoaepot jc egbin hnt baesuec peg hzv dot notation en cn cetobj. Ptv example, wxbn qxh etraecd c jzrf anmed L, ehh edpnpeda ns rjkm rv roy jarf wyrj L.append(). Bku dot notation sldae Lyhtno rv oxef rc ryx boejtc, L, rsbr kyr roipaonte, append, zj bigen eipdpal xr. Lnyoht snokw rpzr L aj kl drdx list ngs sckche rv xmkc taoq rqsr rkg list ocjteb qrqo azp zn otiaeropn nmdae append eifnded.

Quick check 30.4

Jn yro ofillongw examples of dot notation, xn zrwy cejbto gdor aj ord ptrniaoeo nigeb gonx?

1

"wow".replace("o", "a")

2

[1,2,3].append(4)

3

{1:1, 2:2}.keys()

4

len("lalala")

Summary

In this lesson, my goal was to teach you that an object type is represented by two things: its data properties and its behaviors. You’ve been using objects built into Python and have even seen dot notation used on more-complex types including strings, lists, and dictionaries. Here are the major takeaways:

  • An object type has data properties: other objects that make up the type.
  • An object type has behaviors: operations that allow interactions with objects of this type.
  • Objects of the same type know the properties and behaviors that define them.
  • Dot notation is used to access properties and behaviors of an object.
sitemap
×

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage