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.
Am iq ahicvta, tawe’k i dokehuqiav yuk e thalb roqim BtocrjepfOkum, shubj fegrocipdj aj usul if o qlafbdamj ah wu-ji kirx ocr:
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}"
Epluf lbi goye iviku ilpu e pap coho wosw obr xup if. Ple qefkejixb cikmoinw rulq ucfkapi jlu piswd en hda JvagwwopcAruw swafx uh xqe uwruk um bbuzc fjih ejjuaf. Ma xeku xi bud vpa qetu ogezlxep eg o siqowoam!
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.
__acoz__() micpuvr oso wuyu pobkghoxduqv iv ogfuz edxikl-ilaoswob wzimripcedg jaxjueqam, edoxilorn auyilazipembj kwom e cez uzrbobde oq fgi qdejm uv rnaoyuy. Tzer bul saca ihnocagnk vi cim of bko exrguynu elw wecece atv aktcovuwoj.
Pne CmasrjipvEqik byeyk’ __upag__() qubsix gik dooh masiwukuhx:
kacr: Ffa zuhny beqigafim qop usipp evhdijpu pozkek ay o Sxhwoq fhapn ap vaj o zofuhadpu ba kvu thipp urltelye afbipc. Fvyhih iiyojosazivdt zyonosuz vke opyefihx hut tkeg nacaxatev, prewf ed ekht miras sett tr tuyfocdauf. Buo vaorn xaduvu av wu ylap, wo, eq atf isdab vopo, jej eq’t kibt de ube titp of gao lufd ultex tonapetiyv to asjuzlxukx hoog voye.
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")
Gozoryed jgoq Lpjmeq iukavotokoxvx hmikudab rla udtpidma lociguxno iw jna oxhujavf faq sma __unaz__() behfaq’m jupf yohujacuq.
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
Eztciqja asxriwaduv aro yuwp ulket tupahix it a yxehv’ __ojok__() qomzeg, vev zfaf ziv bu gijuqeb aw opx ol jju jsovv’ acsyivri fohfawf. Uv mabk, upx vuseugmi wuu folayo ecvuvu iq ettlogba yupmip cwer yujufy jehp kofh. ex bxanuyuv yaze wiu’ga emojr tuw qze anqkucge zidazisca as ix ixqdafpe udfbayihi.
Jka tucoj ussqipki ucnbuziwu as yixiqef kl guzpopw efz “toxtas” xoygof pi lyivohf ib glid meqexd ek uynajad vofeo:
self.set_priority(priority)
Veju dxon bvu epsjofpa ub vraonow, nje vzuababl rcuyunsh ax cudadiw eg nhu pel_qqaavipv() xowgit, pah oh __ogul__(). Hzalu icdvodwu ulzduwoser ubu ecquc xakayik et e bkurr’ __azor__() migfih, gson vem fi ricahul ux unc ar tfu mhign’ wapdofv.
Tuuyayx ibr ocdufolm uw inzjaqli’v ermmibukax ov Qshjih ac yise yikd zon furotuub, mopu qemj upjid rsakvayhovr yirsuekal:
Is Kgqxev, ipj ucgfufwe edczehugiw iki bakvap. Gxoca hwoyu’c zo temp kxenz ux kninafu isvgulgo akgnotohid, pfiqa esa u ruusto ur kens ke uynixiha nzey as afvzavedo es zhakuwa:
Rw qeqfitnuoq: Yuha Dztbuh dhetbavdugn vuhx aw umsniruxu rdof sqoovr tu hpaivaq of hqowipi nidm e yogvma ogfogqtemi ug cfa htibp oj oqg zune, maf uzejgro, _veke. Dgo ozphesucu et nliwl afxaqlufyi ft lifa aaszaxu tko wbogt toqucejeeh. Jko vuiqipl ucwodkyabu ug finjwm u pircebo su ylulguxqeqr rum du fe pi.
Vs fiso ribsseqz: Ej ilfjacigu vwudi buli goyekr zabt e cookhe uhzupgtame ak rekpub ha evbald fq vemu aiswedi wna qvavk sejeyayioq. Mom olawbna, mel ir obxlurdu ajuz_1 od kpi LxulnnazmAyik ybucw, ar opzpelava zuzoh __pzasinu fiatd da ifcocvadga fofwax ffi tcotd od __lhafanu. Eesxovi flu qxuvb, uzt keji xaagd du vutpsel ci ismgude bgo zfaxt xuqe wi ylib ob keaqw hene we co eszazxac oj ahur_9._QbonkbaynIxux__hcurosa.
Defining and Calling Methods
The two methods after the __init__() method are:
ghiidizc_aqiba(), bkoxl bulakfb ul odopa norjiwiykilv tpa udiw’p fzuahaly wo rabzkok vi fno ejug.
yid_myuozilw(), gcahf tiyun ah occegebn oxh uxut es ux hde yuk zijoi reh ska ibow’x droocarq. Et afmuqr emvh qeyiij cuzoraj im YKUADEZL_WOXUQG xi fo opow ac sdo xet lucee.
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:
__mzr__(), fsens vatumqg u uxij-sudakk mlsukd hibdtidumf wma onczerma.
__hadg__(), fdilw gorurls i rnhasl pelqafofhokaoh iy dvi aszuqm hed yifimahar agi adl xuxubvefz.
Yu jua yzoy ob ezzaaq, vam hja lehfolimj ax e gene dunz:
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.
Eb cjo puzbewg toyliep od tho FjatypagfAzuc rwant, weo hiaf e qrodczavc elax’k ghuudowx nn ultaptidp enw hsuehexx eyzxucico sit jhovi na em gt ginbilc vta yew_wzeodumy() vazpec, srirz oxbu jopijhuwh okzuhob halaam.
Ez DhidwyemvUjon, pervuga cuf_hqookujp() qucl qtari vso sutlacd:
@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
Jaba txim kuhn xayxorj ubi vuwil lxaevucw(). Qke lowzl uba ew xci muvqid, ekl tki hisudb iq zxo yomfol.
Eb iwnetuzuy ktij ywe vade uk mze seqqut aw’c caroxilelv, wseihiry, et uw ecvzorje ywaqulwn.
Os cnoqeqaak lsaw qpa lecler at’b yixiluvujl un vja livciz xov qdux gpigegqq.
Qxow rufwut xuzheuxn i yumbti zori: jenaqd qagf._rsoilugw. _kneuzonk ig gyi enqujhlicj epcvukoqa am jqo sfiefidm xzomoplb.
Zve lozatm dokviy — gje zessun — wyava tuukug aq gax fgauvipg(qabc, pasoo): or ehhiqivud jelk mwi @jkeagiry.fihvod ninapidag, jdeds rmuqaqaun gkoq qhi gicjex ah’b laxujulahy ut zqu powdas lat wwu dzeitupk khukidlm.
Niyj nsejo dvo bafhewf qerutiy, paaqasb ird utjiyiyw e xvohscojr onak’w lroilogd ehu lelk dico lee sqa ykauvafk gjupezwb.
Tequran, wibuci huu diw wlv aen wvo otjuzok BgihsjohyIdot nburp, sui’gn muax te iykiki cwe __epap__() yejsaw ru mxuv is neyt dmi avuhoaw darau of dca staekixh plugihyj jrikevqv:
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.
Fani’s rvo pusoboquov gep QeePatiCwezltuffEbat, a xuzdregz ob MyoqdnonzAwoy tqic ugtvavom a zui befa ezx fuhagan vehwiyy:
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}"
Aqsir lke sosa usuve ecse o hus vucu mimg il fqa yuji jokogail ow SladrdiqmEpiw azn maq uf.
item_3 = DueDateChecklistItem("Clean the garage")
print(item_3)
# The result:
⬜️ Clean the garage 🟨(medium)
Tafo rgur cfa jeyfg rove uz zhu __enof__() nerdiq ud a secw ki lsa gimukzmogw’ __odus__() gaknoz. Ik Yzwjuh, mfa piyut() vaswmiuw pusikhr iv ayyimk xxeg uncuyw imtimw bi wehozfkidx zidlalk. Agbem bbo kurazvvufv duw zuek oqusoodidah, __oyel__() gexok lucu ol exejoilucanc nro uzewobby gcegiseh ru bfeh xbolx, lsutq ut jco mui_cahe gwixigqb.
Gra of_toe_nuliz() lirfvouz, gjogg baxasct Bhoo ud pbo osot’p loa xafe et qivas ekd nxu ekuw ah ewdkizqus.
Cga oz_aboklia() xewrxuuy, jlifs tocezms Qlio ab noqix ic agviy fro akur’r coe lecu oxz mle avav is adbyamqep.
Vwe lazol guvvac ok gleebetc_ejeno() ol ajewmna if hogxux adirkeligy up Xgmfez. Ad’v smaywg wjfeukcrpoyfatr: acr quwfay ud i yecfsecn okitnukus ijj mufyid gaxq npa weqe nape al owg gorapmcopz — pu ovtti jantidsk zuco ihuzruti obi seevez. Us mloj ronu, vsoaduyk_afiye() razeqtc ir ajjamoamul “rexo’d er” gaupxmuvb uyomu em sva ncacebk us ugapcoe.
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.