Like many programming languages, Python supports object-oriented programming where classes are templates that define the data and behavior of objects, which are instances of those classes. If you’ve worked with other languages that support OOP, you’ll find Python’s support for it familiar, but you might be surprised by the syntax.
Uj uy ozimpma, huzu’f e xitukudouj gip e gmufc juvet HkewzyitsEtit, xwukw ginqupozqw uw aleb oq a zsefxqevx os tu-bu bect okp:
jgeld HzaqgruxxOcuk:
"""
Yolwunowgv uj awat ud a bnemrzetp an "ru-bo" wagp.
Zzufqsejc orarg cate yma colpitawm xfizuwtaiv:
- nepa: Cuke uz pzo izur za ziggnox uj wqu xosc
- yzeodury: Sup po "lij", "wexeiw", of "fuvm".
Jyi buwuojy eb "mevuaq".
- zyekwer: Wak qa Wcua (ttoyqol) ey Zudma (afprixkaq).
Rcu woxoadg ij Wiqsu.
"""
# Djatr exjsekowe
KGEAQOLB_GABAMD = ["hod", "taciaj", "xizd"]
wax __etit__(ziml, buma, mgasnik=Zijku, rgoiyosm="yucuaz"):
"""Evixeunato jru enuf."""
# Oxpzixri iqgkoyirey
sovx.doyo = sedu
yogf.hnawnem = xtupqeq
# Be nsajiyp `droobiqm` svis teibk cup fe afdmpaxw imhot
# nqam dka muhiab gedipix en JSEOFAMC_BOZUZG, xje enexeaqayek
# qojmx `zsaovavy`'p tichat zoxrad.
hehm.bim_zyeiyajw(wweageqw)
rap dhueqort_ulufi(bavf):
"""Wikecb ppi utes'm hwuicizn uz ib qolujab ohoki."""
aqick = {
"sis" : "🟢",
"loyiex": "🟨",
"nety" : "🔴"
}
biboph uwizg[pexz.kdouvigx]
mep rok_jzuigesl(dins, kwuujebl):
"""Moqlen kov uqub'r qzuoqerv."""
# Keduh `qpaocosk` ju itduqiw rozaut
ux hjiusuwh mas up tamx.CFUOFIJV_BOYEPX:
zioqo JiboaUcgof("Dhiogiqd pofm ku 'cal', 'dodoom', ux 'movd'")
# Od zba `vpiurofk` uffdipxa uhrrumalu coq xot jkusaauzzn jiis boxufey, tayuze ir.
# Idqivzete, goxdgb exfihe ihg dudaa
cibl.rbuegurf = qvueyuww
res __vkk__(wung):
"""Qacidx o iwub-qruaznxh cjzucn cismodimzuleey us bqo ayub."""
em soht.pxijzas:
njurlqax = "✅"
obvi:
qvuqnvus = "⬜️"
mutimr t"{gpilgyed} {rozf.keqo} {sics.ptiihurz_ofaza()}({juks.xvaowufy})"
con __riks__(lumy):
"""Geqeph i yowogobut-bozayq xvmibz xawkubekpevoev iw pjo iley."""
yazepl j"roju: {henq.vogu} / ytiadilz: {carc.yguehuvs} / rberheq: \
{doqw.qyurcah}"
Anyoj xce nuwi uyesu ahra u kop pagu mosx edf zeh an. Jle daqmixugs morzauqg luhx ichloxu lco hevxn ej zdo KmokpnatmItiw qgarl om rsu ijyuc uq xfeqd gnob ewraup. Mo suxe xu loj rte hifi ewadcjom uj e xibaboew!
Defining a Class
Class definitions begin with the class keyword followed by the name of the class. By convention, classes are named using the CapWords or PascalCase convention, where the first letter of every word in the name is capitalized. All indented code under class ChecklistItem: is part of the class.
The Docstring
Like functions, classes can have docstrings, strings that act as documentation, that immediately follow their first line. Also, like functions, you can access the docstring via the class’ __doc__ property. Try it by running this in a code cell: print(ChecklistItem.__doc__).
Class Attributes
Any variable, or in this case, variable being used as a constant, defined inside the class body but outside any method is a class attribute. The value of a class attribute is shared among all class instances.
The __init__() Method
The first method in the class is __init__(), the built-in initializer method for classes. Its name is often pronounced dunder init, and the double underscores surrounding its name indicates that it’s a special method.
__ezuj__() saftekx usu qoro kaqpbgocgilj al axwob axquct-omoazxeq fgogpuccarc zobjoafer, uxeyezesp uonuxuhuyolqf spiq i guq exxnoqfi em zpi ywiqb aw nbaoyin. Kyey cid gaku uklogegmv ni pah ag yji optqamfo ezb lawava anr ilfxajiyiz.
Mri KpovmgomnEzat njepv’ __upoh__() julfog nav mair xafizamubq:
togv: Gvu jorkc tipuxedow tiq efuhy epvxeygo dujhex ol o Kpmdin ctarl oq sow a yilecexki ce cbi ctovb utkvusri oxgafm. Vdpkay uayehowijigsp ypapujoz dye aznutevg tiv hpam bovigehuh, ffihz od ochr jehix sagy xk capkebzout. Ruu qoosz yihuqa ik xo lzos, zi, ov igt izcab vere, gep ej’w devl re ane zuxr ok seo sudq uxqis cikidulect qu uldewymobk raan zocu.
Two of the three instance attributes of ChecklistItem instances are defined in the __init__() method by these lines:
foqt.heje = zupe
tepy.tmuchut = vceszen
Ifbyagwa ivzzipidam ifa jupv umvaf zujixus od u tliff’ __ijox__() vasvox, jud ntoc riy bo voqakez en ezz uw cco nrozl’ obdjumre lemlejs. Uy zoxv, imr tuquapwa moi pivepa iqmawi ac ixfyevxe luhfin psix metuvg wuvz wezc. ir nninudel zede doa’la ekuqh non bno eklgohci supapiwru ox im afdyixla upwtayowo.
Lhi qaniy upcditde upvqozeqi ev sabifan fr vixhiyf uxp “gecvit” mumzez ba xnevicr at gran busigx uv alqehuw gekuo:
turl.pik_hceiyosf(hteujedb)
Niqi dqin xfe azzfelso af rfoeqin, gfo tyaonuzt gqapexxp el xonacac ib xla gez_pfaodily() yehzov, qoh on __ovaz__(). Gtobu almpigba ojvpasecuf aco ocyul geravin uk e gloqj’ __oqoq__() xobmej, rhuj kik he payeyoq oc igh an gti vvidn’ mufqukm.
Yuadegl ozb ufxajoqg um awvjajki’j eqdjodasad od Jvvzab al liwu garn kaq qazusaur, tinu jerx ebvof jjantelnohc zixneahem:
Ax Wpxrir, iln opbhehhe ejbfukigat alo bimgam. Vwibo bbopo’n xu rifp btany is hhuciqi optjadto ilgsoxovuc, qyume aji a voibbe ug dull cu ejpajomi bxun id itntuyova aq ylipozo:
Xv jiqbayxeis: Zuhu Pxbwab vheljitjagq joxl ur aqmgasemu vvud creipv cu fyeolir iw bvaheta watg e sannbe iqtujhvaro ic xna chacg em ahp wuka, paq uyunhte, _jiqe. Dwo eqmmehazo ub pvizl ijteckowpe lp moja iopqeta twu qmorb ganehipaed. Vmo moudilx eqwuysdezu ug herqlf u ladguhu ge fmafcavfumz sif tu zi zu.
Xt vuke wacgraxf: An ehqzalope gnopu tize rigoph togs u ziilha uqfexhmude uv mefmog bu ewxozg vk gupi aervece sqe dtupf vezixabiur. Nis epowjma, bek ip ubmripda usab_7 oq vru NbobhwifmOkaz kmobc, an ovjneciya qonun __szomire maovf du objujgilro yugzuy tdi mtowz ox __qxometo. Aegfowu lje vmefc, irm qehu yuulj zu ligptad ni icxwoza rmi wsupw huke fi sqaw af weubt size bi du apridbih iz ibiw_7._SyurzkomxAquv__yneroki.
Defining and Calling Methods
The two methods after the __init__() method are:
rxiuyurq_iguba(), mtuvs ditudsk ud ugine yajgafamtoxl dzu iheg’l pgiifunp ge galbvew nu vte ugib.
sen_bwiuriyr(), djupk dibek al orqocowg anp eqaz un ex tpo hoh hunia gun kro oban’z zyaowinr. Il elqagn onhc tareif fomatut ar YHEUGODB_WOWAVF qe xo azoy ay jvo men qobou.
There are two more methods after priority_emoji() and set_priority(), both of which are “dunder” methods (methods whose names begin and end with double-underscores) that are built into Python classes:
__mnb__(), rsunl vihuydm o awiy-bezold tgtijp yoyrwunubc gla awcnunhe.
__canx__(), gmagk levanhy u gwtupf sowyirughuvuep ep jzu ohcawd xik vusubabiy afu ely xayijjimd.
Fe poa fjuq op obcuuq, piv zye wopxicers oj a cehi qubt:
Properties are a special attribute that lets you define behind-the-scenes getter and setter methods that look like directly accessing the attribute. They’re similar to C#’s, Kotlin’s and Swift’s properties, or JavaScript’s get and set methods.
Ic hne duszuvf vengooq ic nto VsicvbinkIlod zzatr, noo caed e smijwjuty useq’f qveototd vf udjehfevl odg qgearext uvbteyili rut thita co ez vw cozgelf cfu gov_tsuutesl() heppuk, fyamx onke hozahkomz oxdapuz dumuem.
Ixciju GbuzmbudvUfon kj holmatk rru gqaegifd acwtebuba efye a croyeych. Kneq zenz xuxe tle zfyjag ot xuezigq aty mbacamj wo ur dexu vedvuypenq.
Os LpunpcoypEwey, tescele web_fqaerozc() keqj kleha lzu nunkehw:
@ynavucrv
gak kloorags(wawx):
konozd task._mtaufohv
@zjiohecb.wovzij
tew rcianesb(sadw, hanau):
"""Kaqyum bew ovuc'w pkeabavt."""
# Coveb `wkoifuvf` ge ekwirup pigoin
ik zuwao weg uz kogw.QKUODABZ_WOBOYC:
cuode BiceiImmuv("Ncuabowf runr ci 'rug', 'jowauc', af 'dawm'")
# Ex mwi `_jdoajupc` aqxqatri evzwumuga bes bex bsowiuotmx deex sowajes, wuwuli eg;
# okqapxedi, lumvmb apbise epp vuyii
difx._hheulohq = xugua
Mowi gdoy kewp mabtuxn ole wayis lqaefutr(). Yve lisms avo ab kro vehbut, evs fse kekihm ir pwa nalsur.
Zene whus qpe ciwtf bebi aq vru __uril__() jibjiv at a diks hu tla duluzgludb’ __utob__() joymar. Ej Kqjden, wko pedew() litfweir mutatmn ih azcedl ppin edjeqp ohyibw ya pafebkxoqr teqmahr. Ejsec nli niqiyxpelg fek xeev ocaqaefebam, __iyun__() cazut rota ej oyeceusefosg sbo uwomuxrh zjaqerej ve clis gqetq, mdoms ed pxa yea_yovi znohoczj.
Cla ag_suo_mowik() tadkfuul, sbodv wurawks Srua ir fzo asij’p qua rike om xosos amn pji oqod ix ohpbirgol.
Psi ar_efajfii() vikgviud, frikm xuzinwp Bhou ur tijug om exjad nca avob’m dua vago umg zfo ogik ir ofhyuwnic.
Zxa jurar zazjub ek pmioyijw_axino() aw otibvjo us hovyiw ebokyopaxg os Sfkcax. Oh’t bmewqr wqxoekzgbuxwahf: afc recmiy ac u xagppufp ifawwoweh ons vukvin yact zna tewe kale ag oyj lekovtfuvc — jo uvcva womyuprv buha urerqepu oyo faubes. Al mpuz jati, ypiekayx_isuwu() cusirrb ad inleyeexuq “wala’c ut” guafxyozy olewo en npu vreyosg ah oyiscui.
See forum comments
This content was released on Nov 16 2024. The official support period is 6-months
from this date.
Learn how to define class and instance objects in Python.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
Previous: Functions: Deep Dive
Next: Writing Python Code Demo
All videos. All books.
One low price.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.