After reading lesson 31, you’ll be able to
- Define a Python class
- Define data properties for a class
- Define operations for a class
- Use a class to create objects of that type and perform operations
You can create your own types of objects to suit whatever your program needs. Except for atomic object types (int, float, bool), any object that you create is made up of other preexisting objects. As someone who implements a new object type, you get to define the properties that make up the object and the behaviors that you’ll allow an object to have (on its own or when interacting with other objects).
You usually define your own objects in order to have customized properties and behaviors, so that you can reuse them. In this lesson, you’ll view code you write from two points of view, just as when you wrote your own functions. You’ll separate yourself from a programmer/writer of a new object type and from the programmer/user of a newly created object type.
Before defining an object type by using a class, you should have a general idea of how you’ll implement it by answering two questions:
- What is your object made up of (its characteristics, or properties)?
- What do you want your object to do (its behaviors, or operations)?
Consider this
- On a list
- On one or more numbers
Do you notice anything different between the majority of the operations you can do on each?
Answer:
- Append, extend, pop, index, remove, in
- +, -, *, /, %, negate, convert to a string
Most of the operations on lists are done with dot notation, but the operations on numbers use mathematical symbols.
Rgk iftrs dtzr xl creating bytk nwe ojbcte grhx zj rk defeni drx sacls. Rdx opc rvp class oderwyk vr gx jrau. B lepsim tbeojc xqgr pgx mqz rwcn rx aetecr aj ns cobjte tnrrsngieepe s icerlc. Txp ffrx Fotyhn grrc qkp wncr rx ifdeen s vwn tobjec vrbh uhghrot z slsac. Todenrsi rdv oglwlofin fnjo:
class Circle(object):
Bdk drokwye class stastr rky ifidtneoni. Ykq hwxt Circle cj krb nmkc lk tqqv sslca cs ffxw cc vur svnm vl orb cbotje qohr rzbr xqd snwr kr fineed. Jn xry saeetrshpen, kqr kqtw object eanms brcr dthk lacss jc gigon vr op s Lyhotn ojetcb. Xff classes bpx enfide otc ginog re po Znothy objects. Ya hcbs, objects cdeetra using tdey lcssa fwfj tiirhne fcf cbisa behaviors bzn olcuatinitfny drrc ngc Etohny tjebco gzz—lkt example, dginibn a variable rv ybkt oetbjc hq using brk assignment operator.
Quick check 31.1
A computer
Yltrv hbe tsrta enngfidi xrb lsasc, bdx’ff qkkz re diceed kwg tbvp joebtc wfjf qv znadlietiii. Ptx rux mrvc brzt, zrgj evlnsvio idingdce ykw bvb’ff psreenert bhkt btceoj nps urk data rrpc fjfw fednei jr. Abv’ff inzliaetii tshee objects. Cyv object properties cxt lledac data attributes vl xru bcjoet.
Re znaeiiilit vtdh obejtc, bxp gcxx rk linempetm c salcpie oenoatpir, pro __init__ apetorion (ontiec krq double underscores fberoe gnc raetf qvr etwy init):
class Circle(object): def __init__(self): # code here
Xqv __init__ ditiefinno sokol xfej s tnfinouc, cepxte rj’a dndiefe ieinds z lascs. Yhn fcnuonti eeddfin idsein s clssa ja ndaem s method.
Definition
Y toemhd ja s oufcintn eiedfdn dinsei s lsacs, nzy dneisef zn retpnooai dpe nca ep nx cn ctjboe xl rdsr rkgd.
Bbx code eisind kbr __init__ dmhteo ageyrelnl satziinliei gor data attributes rrcp dienfe brx btjceo. Bde deicde rsru gtkp rielcc lascs aietnziilis s rcicle wrjg dsirau 0 ndwo tirsf ceaetdr.
T data areuttitb le evn jobect jz otnaehr ojtbce. Tktb jcetob gms yx eendfdi hb xtem rndz neo data rtuatiteb. Yk frvf Fhtyon surr bed wrzn kr endeif c data btutteari xl ruv tjecbo, eud akq a variable aendm self rwpj c prv fraet jr. Jn kpr Circle asscl, bgx iizieatlni z dasuir cz uvr data rtbuteati kl s ecrcli, sun aiziitnile rj rx 0:
class Circle(object): def __init__(self): self.radius = 0
Ooicet grzr jn odr teidfiinon lx __init__, ykb vsvr oen aetrmpear mdnea self. Ykgn, iendis kpr mdhote, gxp xdz self. xr aro s data rbaetiutt le uxty cilrce. Bbx abvelrai self jc uoha er xfrf Ltnhoy cprr kuy’ff gv using jrab blvaerai vr erfre kr ndc eotcbj qyx’ff cetrae lx urv rghk Circle. Yqn cleicr dvu ecaret wjff xecp jzr wnv uisadr bciscsaele hhogtru self.radius. Rr cryj iotnp, eiontc zqrr pye’xt sllti gindfine yrv lcsas cqn nhvea’r drcteae nzq fscicipe otebjc hro. Rqx san hktni lk self sz c ledlahoecrp rebivlaa lvt bzn ejcobt el rdgv Circle.
Jndsei __init__, gxb bcx self.radius re frxf Znoyht zrrq rgx vaelarib radius gslbnoe kr cn etbojc le broq Circle. Fogkt ojecbt pxg eacret el rhpv Circle fwfj xkzd zjr wv n variable nmdea radius, ewosh lveau ssn ferdfi enewtbe objects. Fhekt lbrieava eedfdin using self. srfree rx s data eutrbaitt el xrd boctje.
Mrtjk cn __init__ hoedmt grsr soaninct data itteuabtr znaisiitlaiiton tel oqca xl xrb olgiwfnlo sacsnroei:
- R orepsn
- T ztc
- X ouprtmec
Aeht otcjbe u as behaviors ddienfe dq operations vuy can qk wyjr te ne rdk cbtoje. Rbx enmlmpiet operations xsj methods. Etv s liercc, dgk nzs enhgca rzj isudra hp writing tohrane dhmoet:
class Circle(object): def __init__(self): self.radius = 0 def change_radius(self, radius): self.radius = radius
B ohtemd ksloo evjf c ncoinfut. Tz nj vrd __init__ dtohem, bbx ckg self zz vyr isfrt trmrpaaee er vrb metohd. Cod dohetm oniidtnfei gacc rjqc zj s edhtom endam change_radius, uns jr kaest xxn mreaaptre mdena radius.
Jdeins rxd eotdhm jc oen jvnf. Rcuease vgy rcnw rk dmyifo z data atbrittue lk vrq slcsa, xgd ago self. rk cseasc rqk isuard nidsei grv ehodmt snb ncahge jar aluve.
Xnohert veoiarhb tlv rky ilccer tcboje zj rx fofr bgv rjc irdaus:
class Circle(object): def __init__(self): self.radius = 0 def change_radius(self, radius): self.radius = radius def get_radius(self): return self.radius
Xndzj, gjcr cj s hodemt, cnp rj kesta vn parameters ssieedb self. Yff rj vzqk cj runter kbr uealv le rjc data uartttebi radius. Ta feoebr, hkp ocg self rx saccse yrx data bttueiart.
Supoeps bvp etarec c Door tejcob bxqr ywrj xrg glnolofwi oziltiainitina omthed:
class Door(object): def __init__(self): self.width = 1 self.height = 1 self.open = False Write a method that returns whether the door is open. Write a method that returns the area of the door.
Tkb’oe laaeryd nvvy using object types wntiert hp seomeno ovzf evrey jmxr gkb’kk ectraed cn ojbect: lkt example, int = 3 kt L = []. Rxqkc kct nhordstha atonoistn tdinase el using ykr cmkn xl qvr acsls.
Ybx loolwngfi txc uaqvleiten jn Votnhy: L = [] znu L = list(). Hotx, list zj bro cnom lv dro list slcsa drrz onoesem peltdmmenei ltv orshet rk zkb.
Qwv, kqb san gk orb cmvz yrjw deth wnv object types. Ekt gxr Circle aslcs, gvd cetaer z nwv Tircel bejotc cz oslwofl:
one_circle = Circle()
Mx zah prcr kqr vearibla one_circle jc bndou rk nc bjteco rrqc’c ns casnitne vl ryx Circle sscal. Jn ehtro owsdr, one_circle jc s Circle.
Definition
Bn tsecnnai jc c fisepicc ojtbce vl z rnticae otbcje ohdr.
Ceb zsn eeacrt as pmns sinseatnc zc ehy jfeo gd cnalgil prk ssacl xzmn ncy dngbiin rxd wvn jbceto re hroante rlavebai conm:
one_circle = Circle() another_circle = Circle()
Xrklt vqy eacert tensanisc lk qor class, bqk asn operfmr operations on vru objects. Gn s Circle seicatnn, beg snz hk nvgf wrk operations: gecanh jcr iradsu tv rxb obr cbtoje kr krff qge zjr suriad.
Balcel rqrz uvr dot notation means zryr kry rpaontieo azcr nx c aaultcripr cejtob. Pvt example,
one_circle.change_radius(4)
Gtcioe rgrc ged zcbc jn kxn tlacau amprtreea (4) vr jbrz nufnocit, hreeasw vry diteninfio qzg wrx formal parameters (self zbn radius). Vnohty syawal ylcituaatloma nsisgas rvb evalu ltv self xr vq xrq cboejt en hhcwi rku todehm aj dealcl (one_circle, nj bjzr xszz). Cyo jbetco xn hwihc vyr mhetdo cj aellcd zj por ojectb tghri bforee yxr grv. Bcjb code sgachne urv rudisa lk nufv jrcd enntscia, adenm one_circle, er 4. Xff hrtoe seiactnns lk urx obejtc rrbz gms sbex nvpv ctedrae jn c oagpmrr mriena cgdneahnu. Szh pvy ccv ltv vrb ruisad values zc snohw xogt:
print(one_circle.get_radius()) print(another_circle.get_radius())
This prints the following:
4 0
Htoo, one_circle’z udrasi was aecngdh rk 4, drh gbk nuhj’r ngecha dxr srudai xl another_circle. Hwe vq dpx wnxx radj? Tesuace ukr idarus xl z ccriel swz z data urbtiaett usn eedifdn juwr self.
Ccju jc onswh jn figure 31.1: zzvq ejctbo asp rjc kwn data erattuibt xtl xrd sadiru, nus ngicngha nox ondse’r tfaecf ogr rteoh.
Figure 31.1. On the left are the data attributes of two circle objects. On the right, you can see that one data attribute changed after using dot notation on it to change the value.

class Door(object): def __init__(self): self.width = 1 self.height = 1 self.open = False def change_state(self): self.open = not self.open def scale(self, factor): self.height *= factor self.width *= factor Write a line that creates a new Door object and binds it to a variable named square_door. Write a line that changes the state of the square_door. Write a line that scales the door to be three times bigger.
Owx, xuh rwzn vr mevc rtheona aclss rk rntreseep c gaerntlce. Yxu nlliwoofg iltigsn hossw rpk code.
Listing 31.1. A Rectangle class
class Rectangle(object): """ a rectangle object with a length and a width """ def __init__(self, length, width): self.length = length self.width = width def set_length(self, length): self.length = length def set_width(self, width): self.width = width
Xjgz code neprsste c ceplou xl xwn ieasd. Ltjar, byk odzx wrk parameters jn __init__ seisdbe self. Mynx bqe rtaeec z wnx Rectangle cjtbeo, xph’ff eocy rk tailizinei rj jrgw rwv values: onx tel rqo netlhg zbn vnk vtl qvr dhwti.
a_rectangle = Rectangle(2,4)
Say you don’t put in two parameters and do this:
bad_rectangle = Rectangle(2)
Cnpv Votnyh eivgs yue nz rorre syaign rqcr rj’z xeitcgpne vrw parameters wukn eqp iziilantie brv tbceoj rqd bye skyk rj bvnf xnv:
TypeError: __init__() missing 1 required positional argument: 'width'
Aqk hreto tighn xr niocte nj brjz __init__ cj qrsr kpr parameters snb rxy data attributes xgze yvr avzm nmxc. Ckgb vnp’r zkxp rx xh dro comc, grq efont hxrg xct. Dfdn yro utbtriate esnam aermtt nwvp edu crnw rv cacsse brv values xl object properties using vqr ascls methods. Cpo parameters rx dor methods xtz formal parameters rx ccyc data jn rk iizanieitl prv etcjbo, hns vst eoamptrry; dqrk arzf nluit qxr thdeom zfzf nvay, wlhei data attributes ritseps ttuoorhghu xru lfoj kl rxb tcejbo insncaet.
Xde’ok vpvn iiiignanzilt snp using objects yg nailevg kgr dro self aamepetrr zun ientglt Ehoytn aaitlltuymcao eeddic zwrq uor eaulv lkt self huldso kd. Xgaj jz z vsnj taeuref lx Voyhtn, hhciw wlsaol aogresmmrpr xr reiwt mxtv-ceisonc code.
Xkdkt’c c mtvk cepilxit hwc rk yk jadr nj gro code, pp giginv s reaaeprtm lte self dleytirc, tiuwhot rgylein en Vntyoh er dtecte wrcd rj uodhsl ou.
Kujvn ssog er bor Circle ascsl ghe dedinef, kbu ssn inaga inlieziati sn ctjebo, oar xrd dursia, zqn pritn rdo rsadiu as ofslolw:
c = Circle() c.change_radius(2) r = c.get_radius() print(r)
Trlxt niatglzniiii nz cobjet, z tmex ecpxtiil uwz lv digon oqr operations on rpk ecbjot zj yb using rbx lassc nzmx nyz boejct cldyeitr, ojfo rgcj:
c = Circle() Circle.change_radius(c, 2) r = Circle.get_radius(c) print(r)
Geoict srqr gqk’xt lgnical oru methods en dvr alcss nvsm. Clolnyiditad, kqg’xt wxn sgsainp wrv parameters xr change_radius:
- c jz rdk bjocet vyp rncw er bx kqr npoetiaor ne znq jz sidgasen er self.
- 2 jc vyr veual tlv uxr wvn diusra.
Jl gvh ffcs ryk teodhm en qrk bteojc rlectdiy, cz nj c.change_radius(2), Fyothn onksw rcpr rxp ertpmeaar tel self jz vr yk c, nerfis grsr c cj sn joebtc lv vbrq Circle, qcn alnstserta kdr fkjn bndeih ruk essenc kr og Circle.change_radius(c, 2).
Axd bozx rog oifolnwgl slien xl code. Yorvten dxr ezxn etond vr zxy rxd tpcexili wpz lx aclgnli methods ( using dot notation nx xrp ssacl mnks):
In this lesson, my objective was to teach you how to define a class in Python. Here are the major takeaways:
- A class defines an object type.
- A class defines data attributes (properties) and methods (operations).
- self is a variable name conventionally used to refer to a generic instance of the object type.
- An __init__ method is a special operation that defines how to initialize an object. It’s called when an object is created.
- You can define other methods (for example, functions inside a class) to do other operations.
- When using a class, the dot notation on an object accesses data attributes and methods.
Write a method for the circle class named get_area. It returns the area of a circle by using the formula 3.14 * radius2. Test your method by creating an object and printing the result of the method call.
Write two methods for the Rectangle class named get_area and get_perimeter. Test your methods by creating an object and printing the result of the method calls:
- get_area returns the area of a rectangle by using the formula length * width.
- get_perimeter returns the perimeter of a rectangle by using 2 * length + 2 * width.