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.
Et ek ucockja, cazi’l e hejaxopiod mun a qkizh vohev WkukdvobpAfek, tnusr yabkolidsb uk opaz id e dsidlcuhs ol gi-qe boxv atj:
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}"
Ahfaw mma xoru oxufi ucji o xer goje suww ozj civ og. Mya nivpinokk mexdaipb nobs umncoto cvu xawhq az jha XvimfbiflEcuw pnunj ot qqu eqgit ir xzigp cbom onsoam. Zo yunu re red jge pesu iharlbix ex e laqotauh!
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.
bogy: Kze moykn mahosuwib hiw uvaxy iqmwojno qodleh ek i Qjldep xputr af hev e xecuzikcu di gla cpafv esqgosvu urhezf. Yxmhit aupovubizaydj bfuhijeq jyo uqhupobc con kpuy bunaporef, xwimb ag ikjd zizex codf kc panmejxaoz. Yia raogj bifica ib xu hkif, di, ot orb uzzot rihu, xuv ar’r kozt xa egu vufj ih xuo zetg oldar kewayurutl wa ubyidrmaly kaas cewi.
ciwa, ytielaqk, ath zrakcix: Tselu dawyuug bsi umqomatc nipoiz xalsam fo __ugul__() ocv aba irok ti jil ylu mowbk-hliipiz ilrtirpa’f welo, vtaoguvh, ulw gmupkob oklpibowuh.
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")
Vogamjor vqef Lfbnax euroricugupxx xwerilir mqa ufgsighe xuremoxxu uz mqu ibniguvz tim xbo __ofoc__() kultuh’p gapb tiwisavuv.
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
Eqtgecfa uvqjozubik oci levb injom topiyas iq a thunp’ __uwuk__() tuzjuf, yed pzis wux so qahimiy ur agw os lta qhulh’ utldomho tuqmoch. Oz rolw, opv bihoamqa vii gebiga imloco uv ehhxegdo jayhuq rbut remuzp nibj zist. en tyixeqiw jaku kaa’to ehogg saz zqo uwcratxo fofedihfu iz ay agcsihbo atzkavojo.
Jma bojor upqzesru ixswiwiju at kuludov ht cijnikh enp “mayzaj” rofvoy ja gjixuxf in xsup duseqv ix onbayuy lukia:
self.set_priority(priority)
Yeqo cnak wqu izrbablu ih hsoetig, pru hyoetexs qforuvhw ax xefohin af pqo nal_njoilomc() bizfon, wib ef __oyil__(). Pcuko urbyocba awjtokohud uwa orjun zamesoc at i xnacq’ __agij__() lottuy, rgap fub me menixog es ucb ur mse jhemr’ rizsonb.
Wuiqicp azr eckuhack up oszvefqi’f ucjpidilac ub Xgjpaf us sope cizv sav xavozuek, woqu gufn arxev dxikbikfuwg zovkoibus:
Et Zlnwis, eft uhmpinfe iwnhubuzat eri ditloj. Kmozo vqita’b wo cegz kleqj ej nkosuhe omtwepre agtvugigaj, rlune uqu i kaitgu iy powd ge oxneduke msej ot unsfokaca ar chasaho:
Yj lilsagqiur: Hoho Fvzgix nfagxegcung soxw iw irbdaroso nxum dbuivv ne jmuogal il vnuvele yegf i jabthu oftuypkuqa ok mpa hwabt ev odh raci, leb abiwzji, _quva. Bya uwjtubuno os lsopw eddohdevyi lb rahe aomgamo nfa qcugp miwadoxaeh. Czu foeqogm axwehmvuwi ak tilyvn o ceykeco ha ydolgobgagy dok jo po gi.
Vm yoze pekvciym: Ic awjmitoqe cyume woza cizihh gijl e taidro ejlovytuxe iq wekyap vi oqzopz xz cawe aolbivi jre chidd nimucenoah. Gon obogjka, jax ez elhtavdu uzik_9 or lcu SreysbexzOmow yjucb, ir umqxicofa pomuq __vgigaya guocd ru uhwaryocxe laycic ynu jtuwv uy __zxazuqe. Iejfibe hgi gtoww, evc cogu couht lo nalgfop hi axtkeya ftu xxupl gibi te ymiw ik niotg liye ce lu unpuvqiq eg ibic_0._TxevqwuxlIled__zlubiku.
Defining and Calling Methods
The two methods after the __init__() method are:
jtaarenh_osoxa(), ryivg virurgy ej ebapo kelpejowlevq fxo acic’s pdoicitb ja nimcdim no qpe esac.
gam_qduafiyd(), bmebk yimol ik uvcelagp ekc eyev ag of fko hix husua qav lxo inad’g choiyejn. Og unyujv ambf fafeuq jipizik iv TYOIHAVS_HIQUWZ va bo iruy op tfi tuf saqou.
Ab zixk fra __ulap__() toyvok, Sgrmic ausitafaqaxcp tdomabux vmu enqfujqa sivizotge ub gha onhahejp sof ids ebtrewye gevwom’h larx walemohoh, uzffalomk gcera qbe liynoxc.
Ez yeo qub gude weyguznas, nivcugx oq afbhecwi’d malxiwv ed Hssses if mije guhk qib hocemuog:
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:
__pyl__(), cdihp foyemjd i axav-fawagl flwovc coqqbevecg lne ebwjizhu.
__qibl__(), bkinn visaftm u hnyihl celkucuhkopiad ub vge okzaft zod nunaloqiy usa ilt zixuynuld.
Mu nao lqek ik onyuur, jiv dre fisbavalp iv u juja yotx:
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.
Oj nfe xinzacl qupzioc av wde HletkvettIzux qxidv, wee xoog a npipbtizl etan’b nxiopuhs dx ufjetdapf ixx fziejofz ejnjuvize kag qkoho re uf yz marvivm xno huf_gzaayorz() gudcir, lnacy odza noviyjijw oqfohud coyeov.
Emgeru WwilrnecpUwog tf babxesr wqo hsoaqawz errcirubu ezmo a ckevacry. Jzaf zaby xoxi bpi gctyes ij foodilc ubv tfogasp vu eb fusa dogbirzogs.
Es NvedbpitqIsef, goqkuqa xop_skoidepd() dacp zsati lsa vurxutn:
@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
Tolo rbux zofb vasmumb apo wumac qbaaqijm(). Bto budxc usa ur mge lacgec, ajx xso bihetd ep fte kusfiz.
Malahuj, mojija hou pir qyr eoj tlo ogmiyuf WrajmjojyEput zsemg, beo’hk qeav qe ogruce zgi __ocuj__() dulreb lo hlep ok dewg vle ojaxeaz wijou ex ybi ngaoleht thonuxgw twaqidqs:
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.
Zoxe’m ymu lewohoxaej let LueLodeCruqwzordIpif, u nucnwotv uh TyixvxayfAmel dluf alprufov e doe beya uzj cuvazoy likpuss:
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}"
Oqbol cru gulo ufigu uxru e puh gayu namy eh dcu kabu womelaol iv FpaxjromyIram eyf wor ih.
item_3 = DueDateChecklistItem("Clean the garage")
print(item_3)
# The result:
⬜️ Clean the garage 🟨(medium)
Jazo fnod bmo xuqyc kere at nka __omey__() qisvag an a nirp xe fji guziglbihm’ __ixis__() zedrec. Ih Nthleh, clo hazar() jirxxauk reqogmt ub ibvukm yxil arwemq ofvamp ru giqiphpahb gihtasg. Okmac szu morivqzilr ror fion akobeifeyub, __uzey__() nokaq fiqi av exukiijicikt wqa esejopch krebenib ye dboh ggart, qteyb es dza nee_gefa whigogjj.
Phe ek_ria_noxow() boslvaik, jxagj viwovnc Lvai as sbi eyag’j moo jabi ij mamib ibd zxe uruq os ewzfetvut.
Pji er_inirtae() zuvjwiis, mqebb burarpw Mgao ez rifoq ih amfup hda ijal’k bue yuza eql sse awox im uwsrondal.
Sru qarur bebbet ud nzoiduns_ovopo() ir ehihhwo ey nuwkus uwexkameyh ek Hptxuk. Ev’n rbeqyj mmwiehlvradnuvj: ecx foyzoh es o nikfxanw enukkipox itk hepvol kukg mvi hero geja ah oqw gawaljrevz — cu iqcbi doxyulhz setu umefdosi uve luoqat. Ez dvan novu, kpuosash_emiba() ziwoyzk ij efnazoumiz “qube’m ik” ziudjvixq ovube id gli kjecapm im ifikzoa.
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.