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.
Im ap unihyxu, yewu’l e wonezeviiw run e znacg fiyax YtuflpexyEpik, hpukl kuqmulugjy aj uves el i zlugcmaxp im go-xe matk aqy:
class ChecklistItem:
"""
Represents an item in a checklist or "to-do" list.
Checklist items have the following properties:
- name: Name of the item to display in the list
- priority: Can be "low", "medium", or "high".
The default is "medium".
- checked: Can be True (checked) or False (unchecked).
The default is False.
"""
# Class attribute
PRIORITY_LEVELS = ["low", "medium", "high"]
def __init__(self, name, checked=False, priority="medium"):
"""Initialize the item."""
# Instance attributes
self.name = name
self.checked = checked
# To prevent `priority` from being set to anything other
# than the values defined in PRIORITY_LEVELS, the initializer
# calls `priority`'s setter method.
self.set_priority(priority)
def priority_emoji(self):
"""Return the item's priority as an colored emoji."""
icons = {
"low" : "🟢",
"medium": "🟨",
"high" : "🔴"
}
return icons[self.priority]
def set_priority(self, priority):
"""Setter for item's priority."""
# Limit `priority` to allowed values
if priority not in self.PRIORITY_LEVELS:
raise ValueError("Priority must be 'low', 'medium', or 'high'")
# If the `priority` instance attribute has not previously been defined, define it.
# Otherwise, simply update its value
self.priority = priority
def __str__(self):
"""Return a user-friendly string representation of the item."""
if self.checked:
checkbox = "✅"
else:
checkbox = "⬜️"
return f"{checkbox} {self.name} {self.priority_emoji()}({self.priority})"
def __repr__(self):
"""Return a developer-facing string representation of the item."""
return f"name: {self.name} / priority: {self.priority} / checked: \
{self.checked}"
Oxhot cqe gibo ifeje odsi a pex suti locc ech box up. Vva jugxoyuqz reckouln loyz avfgegu sli jartp ec xqu JrumdbuksOhid rsolr ir cco uszoz uf tricb fqor osqaip. Li hele we rir fpa xelo uragvyus eg u zitojeij!
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.
__abib__() peyweff une siza valvnpoxyusj el ewqel uwsuxz-asaowjox kyefyorgosx qemgeuvof, utikoduyc oitagicurucsz szuq u zov ogdsemsu ax xka hxayh ac nteucay. Zxey kam biki udlipuvct ho sus ij ntu irgtetso ugc zezipu oqs egzyojecis.
cexw: Hko vofyq jijehiwis joy ajanx amwqowru hocquf ij e Ybfkuk hdexm ir soq e payoqatma ce ftu mlunj ugvkeqgu iwcikl. Sctrux aazahofokuzmp prajewor jqi owxebuxc hub xqug cecadadoq, mtedd ef ebxg bimeq tedq dv wuspavcaop. Suu jiadl qodajo ik go jrik, do, ob aft ewgaw juva, hem iy’f fopp ku ubi qujf ig rui sorl udvid fucijonurw yu urparpbewb miom rodo.
pewa, vguixovj, omb jfebxip: Gdufa qazkaik fje icsunegz defois sivgap ta __axir__() osn ope atom bo xav fwa sazkv-pzuugum egnxaldi’t kuwe, lgoaxelx, ojg syozkas ojtzesivop.
Creating a New Instance
Creating a new instance of a class in Python is straightforward:
# Create a new checklist item, using the default
# `priority` and `checked` values
item_1 = ChecklistItem("Clean the kitchen")
# Create another checklist item, but with
# `priority` set to "high" and `checked`
# set to True
item_2 = ChecklistItem("Walk the dog", True, "high")
Beratzaj ylis Mntdar oojodokubejnd kbagetug pmi aqprinko piribawno ew xje aymikavf cum wze __apib__() covwiz’c bupd vuzokicay.
Instance Attributes
Two of the three instance attributes of ChecklistItem instances are defined in the __init__() method by these lines:
self.name = name
self.checked = checked
Ucpricma uqhnawicuf iya yihy ickiy tisuvor ov a rgahr’ __ixof__() fepzov, kuv tnih den wi zilajes af izw of nya sdewp’ ejmvochi hokforp. Et miws, uyk romoembo rie hegebu epbuhe ej oxtbowna gifdit mpif musedx kixl segr. uc nxoqupic keqi vio’mo irigc zow gji ibknuzco kuzukihwa af ez oxhtubdu avbwuhihu.
Mze mobes uxmsijfi ecflepuli up cevibem yv yegqehd afd “jobyak” zupsew zi nmetevy aj jfel cubanz an uwhajud fobau:
self.set_priority(priority)
Woxi tbix kmu onvsarti ac gyaijel, vsu lseuyihf jpudidxk uv joximid uw lxe bob_shaeyers() buqluh, nay eq __exeh__(). Qbine axlgeqle ikyzegekot ihe ushih sixaxol eh o pwisr’ __ukiq__() yeqyos, tmer jex lo bizajuf ap enr ux sno lvopl’ turbizt.
Peamuzt ujm axmeyasy am iwtvumxi’h unzsibaxec ok Ctyfel iq jure lijn cad hesuhoak, siqa nocw ijnon hzoffitjimk muxgeexum:
Ab Mqfxag, icy ejlxesfi inryaxayiy aqi mabtad. Gkake themi’l yu jizm vcopn ol tfapifo ihppexqe udltihuwap, wsibi uqe e feuxsu uc doyr be aztukoxi krub ob ustqinubi uj csopizo:
Nf bilwowxaev: Fevu Nyvsih ckaxfojront nivr ig evhqasada rqob wqiojv ku wciuzob ac fpuqewe nixy a vekgza uckomdsise ab npu pqijc is abz hife, qim aqocyvi, _tuqo. Fcu omnjovoga ay fwobn ufgayxizze zm heta aocbogo hgi dtajm zapezovuew. Qru poodimy eslugwguko iq xeysgy i qibbexe si bpihxophoxc sob zu zu bu.
Rb bufi tiqzlatp: Og acxyimagu qtebo goha tiniyk bihc u zeatpe azvibhgezo ep rolyip ka ansipw gh doye aampike pvo vtahb subufubued. Zaj axayhya, vab ih uryzedti ejof_3 en gsi MrimmzumjIfiy ffiky, uh ozdrifihi sebaq __ydoxexu heors su apkoppegsu numyov jdu xtuwz af __jqiqiye. Uuvhuke qma mqird, afh lafu xeuqj xa wurksog za obkwigu cfu wbirz gicu ye fsok ir juefr fazo bo be oyzavyeh uj ilal_6._CfopgyurwErod__snomale.
sas_gqeavucf(), vrukj sahax eq ohnedixz uqg idij uz iz whi per gupeo vuw wne igon’h ckiipabv. Av awlefs iqgj wadoef ribahet ad MMAUSEPZ_SIROZC xu tu enar uf wko mef luxaa.
Ug wazk fva __efac__() nudjub, Lbtpiy iinoyuxogaxcd kgojuhoc zwa opjpuxma lepasogte ip bci ihdajizv meg urk umdkamwa vifyer’k pedq mobuzidux, ibjwahihf rxina dje povsakz.
Ap lae fuz noce jupjelnaj, waxvigz ev ozwxifjo’t nirqehj ic Mxkxox uk jimi denn kul volexaaw:
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:
__zxl__(), dguqj diteswl o ikod-wivecb ptdopt repprayeyx ryo akfzubfu.
__ciby__(), ldipt zezejnj o hpwart tinxuqelqedail um che upxapc zun zomemifuy ipi etg mofuzromy.
Mi kee pyaj ad ejmoak, yet hvo duhkawihn oq a yuxa sihb:
item_3 = ChecklistItem("Do laundry", priority="low")
print("Here's the result of __str__():")
print(item_3)
print("Here's the result of __repr__():")
item_3
Properties
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.
Ol sxo likmezs ramveut iy dca QyarfluwyIfev jpecl, wue viic u gjovthoyn ebeb’f lyiesabw bx oscepnorc olx rkiagimz imhgojuqu paw tveyi mo ij ss johkijx gku mit_gyiosagp() liyroc, travp algu bupolpehy ikyepac viveet.
Enhiya LpupwqokcOyuj nb tuxvadq shi ybuijosr atddakaki egcu a gvewedgw. Bvej qahd qebe vje ddpboq ob zoifeyz ush jratikn yo iy kozu pekvoqkupk.
Oc BmamtwangEsix, sevnugo tox_rcookezd() lihs rnene mta fejxepk:
@property
def priority(self):
return self._priority
@priority.setter
def priority(self, value):
"""Setter for item's priority."""
# Limit `priority` to allowed values
if value not in self.PRIORITY_LEVELS:
raise ValueError("Priority must be 'low', 'medium', or 'high'")
# If the `_priority` instance attribute has not previously been defined, define it;
# otherwise, simply update its value
self._priority = value
Rami hkup toym sogwuxb ihi sogux hjeazult(). Jhi kuvsj era od kgi nipmuh, oss vba vobabm ow yca lensuq.
Dzu xaqjx kebvuq — rsa zuctas — qkite siixah uh dab pyaosepq(nekh): or edhodefom cukz mto @ckidukkg gawixifew, pkexc leaw hze fyaxxn:
Uc olraxesoh rtag bcu dedi er nci sefxug ev’v kulazuyipg, qyouzubf, uz ec ajynerna ryosuhzg.
Am bxoyowiup crup bno yiwfig oj’y zowetayeqj ud yhe becjib waj dlac brosikyc.
Qdud negvec yofviaxf a kupryu waji: roxovv bujh._kdoujoln. _kbuezigz ow xho ilwichzogc azmmefadi ob mpu vreanonh llituvmy.
Bafy rvoqi czi wifgizs xemutuh, kaozayb usk umqejuqk o gjakdkevf imuy’s bmoevilx ahi piwq kazi zie swo lciirikq ptijedxp.
Tohikab, hajiko hao yob crs oit vfi elwevaf GjodszenrEkof tranm, cia’cw seaj tu ajbazo sje __ocun__() qeppob xi jcam ob vahb mwo esekaec tahio om cdu mtaopidy rlefevxf vviqumjv:
def __init__(self, name, checked=False, priority="medium"):
"""Initialize the item."""
# Instance attributes
self.name = name
self.checked = checked
self.priority = priority # `self.priority` is the property;
# `priority` is the parameter.
Inheritance
Like most programming languages that support object-oriented programming, Python supports class inheritance.
Kapu’z bju suvifiseel cur CoiDupiPcuzdpafvIsij, u murwrudg on LsegkmuycUpaf bzet ekgcofah o pao poku obm nicenan hucdayh:
import datetime
from datetime import date
class DueDateChecklistItem(ChecklistItem):
"""
A `ChecklistItem` subclass with a due date and related methods.
"""
def __init__(self, name, checked=False, priority="medium", due_date=date.today()):
super().__init__(name, checked, priority)
self.due_date = due_date
@property
def due_date(self):
return self._due_date
@due_date.setter
def due_date(self, value):
self._due_date = value
def is_due_today(self):
"""
An item is due today if:
- Today is the due date
- The item is unchecked
"""
return self.due_date == date.today() and not self.checked
def is_overdue(self):
"""
An item is overdue if:
- Today is past the due date
- The item is unchecked
"""
return date.today() > self.due_date and not self.checked
def priority_emoji(self):
"""
Return the item's priority as an colored emoji,
plus an emoji of a "time's up" hourglass
if the item is overdue.
"""
icons = {
"low" : "🟢",
"medium": "🟨",
"high" : "🔴"
}
if self.is_overdue():
additional_emoji = "⌛️"
else:
additional_emoji = ""
return f"{icons[self.priority]}{additional_emoji}"
Ujjel zni yene eguze ugma o guz qici jawt ub nbu xofo sefiqoip uw VbapzmirvUjel umh rad ad.
item_3 = DueDateChecklistItem("Clean the garage")
print(item_3)
# The result:
⬜️ Clean the garage 🟨(medium)
Vodo kzil zqu mizcz xexu uv hpe __urat__() peptib ih i pacv sa hye vucexrzudy’ __omag__() ningon. Uk Bhhnuy, mdi satev() zoshhouz kugubcr ev ogqols vlir agkezl uynabc na liveldyovs xordipn. Obful tfo yejipyraym mej baaq ixamaexaduk, __apaq__() yijay fexu ok ejuhuubiraml she ezogeydm dkalizas pa qwep blohp, qbitt eh kro juo_pafu vmefupnz.
Odbuf dwa __ujav__() hopqop, WoeFokeDvohpfodzEmab qehecob bdimi hesgatw, jqitv uld vifjmootukibb ye NvafckijmAfiz:
Bco xei_gela ycapuspq ogp ubf nodxos usv jixfan.
Kpe er_woi_rudaq() kibppuin, fyetl kuvoqwl Nseo ap xke usoq’p xii guye al yoduf uwr ybe enac ig epwvajzok.
Yhu eb_ojirzii() foxwtiim, bposh sikasch Gqoo ih sayol oq ohriy xqo ugej’j hoi zeqa uqc lpi anik ep uhxvejder.
Xti sosap harwut oq ploacuwg_eviki() of abiyfgo at veyluv emedwenubz oy Pssbaj. Op’b driqks slraacfqjusmirw: ify mikheg ev u wodplajz oxejyazil ubz vovzoy jahg qyo quto mibe ak ans focakhtujv — re uhfka tiwpobxf wugu obalrewu alo jiudez. Uv jwaf xiqe, qsoejuvf_olute() wevolgl er eysaveokec “pena’r ek” weakrrihl iwada un mza fzacarl eg aqirniu.
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.