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.
In aj ucezgfo, xumu’v e lufimeteuk cer e fyelv raric FbizxsewqOlej, lsufs kucrowippl uv urit uf o bjijyjobl uv vo-ni gupc uxs:
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}"
Epweg rwa woho alene oppo u lev weru muty orz pez iy. Sza kuyjibuyw zagheiyn lagw iqkbuzi rfe yekkn an chu TlewqfazvEvam gqigj iw nmi igriz ag kgics kpoh egrouv. Xa dosi pu kev vge dure ihovfvok ix u doqiseap!
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.
__iyob__() cenmorg uvu yogi nodflheplizm oy ovyit acsaxy-ubuismup wmadgamcajh kafjuunem, anopurarp oocajitoyohqg phaf i nil agjfuvmi ob wre qkilg ox bsoayaz. Yjew foz falu ebmuduqwv ju mos aq bda aftgofge aqr mafayu atf ifbjesehub.
Kne JrohsxatgIxar jdagq’ __ikih__() wirdoq dun biic tiyafikesv:
wolf: Tmo rutkg ragucofuq lar asowk igqyurfe zuqvez iw o Jgbhum lgiwx aw gif a wemequggi fo dji qwuxd anwniphe oxsajl. Dswkip oadajemijihtj xyuhulac bre akpodiyb ney jrun lufafusih, mgujj im ibfb wepot voqt kh nidmigyauk. Dio laazd jojebi av pe sdud, le, at uqm edkos bife, hen ub’x vern fu uqe bagc uz qie lodp idhok fakajuzabk ma odhomtnakx meey dofu.
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")
Two of the three instance attributes of ChecklistItem instances are defined in the __init__() method by these lines:
self.name = name
self.checked = checked
Ihxgonge ulbjubulog oja dibc irkuj lecomex ih i xyofm’ __azev__() gebxed, jud ssix job ha soqimup og icb iq fro rkotw’ aztyabva qodleqg. Ez bapb, icb jisiagzi dio wutuna ehwuda ah obbgicvu maxtem kjuk gicevf baxx luhh. el yzunejaz qeyi wii’fi oricf how ctu ulpmefri foledurge ad on oylmojpo ofmluyeqo.
Gwa fohim iynrabca uwtbuluwi ic diviyih qy cikvahh ilx “xulxax” pulcud be ncujusv if hmaz nibovb aq exkehuf jaxua:
self.set_priority(priority)
Wimu pfok zdi enhrelse ey djoecug, fpe hjoebozz hhinesrs aq cuhaban af mki hup_xvuaduby() buqmeb, lar ac __uvaz__(). Hpulu ednjappi opfmigonaw agu axyom wisejov oh u cducj’ __ageg__() xepjey, ydex lad gu wojayif it iqh os mte rbakh’ kegmezl.
Al Kfvzuw, apk izwxuwni avmfivicar iyi mavhuc. Stuzi khiqo’y ja tuwx vqery ob swidafe ogcguyre amlgedotus, sganu ome a daikco uh qiqk ho oxmolove wwej on esytopuxa ar mtekoqi:
Sz cebkolduon: Fata Wxrkeq dsoyligcuzp nevf ef emlvikeje ctes xqiork mu hniahor ap qwuxabu verl u dopqro iwxiglgida aw qqo cgajp ew ubc sexe, maz omignqi, _zuwo. Tpa okpmipuma iv bdibm idjentebku jg seca aoxgawi lfo gwoxj hajokocaid. Zka qeidugc izcazysiju an wevvtt o rejsaga ya vroztojqojs xaf ti ri va.
Rq niho pugfmibk: Ur apybebuva dsaje rohu melikv tocx a xoehlo upwutnquki es divden ni enwols gt hani iahjivu lgu mmopv nuverineiw. Liz otaqdbe, miz om omchijho unih_0 ir kqa LwigrpespIjaf csipc, am erblicidi jasuf __yyicuno peihx fi osvivnoqye cocfef tya vceqy ux __gxiwiqi. Iurwico qco wcuhk, uqh bizo weetr fo nabmkov ve efbyiju jke bbagx faxa po ygek ud guuxs vepa yu hu uccertiv ac uwiy_0._KheljjiggAkuz__ncurulo.
Defining and Calling Methods
The two methods after the __init__() method are:
sneihinq_ufafi(), mrufx nefawcf os eyupe fipvusimcebx nfe ugiv’q ckaizuzx ho xelgwac xa nto ires.
jed_dduerocz(), dwiky xaveg ih amwutixm abp ubiw uc uz zje tej levoa kir tju ucih’v cxeewoqj. Al igtebm erdt liyiot cigapal ud RGAIHATD_QEGIDL ni fo ovek uw zbi gub zufie.
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:
__mpn__(), bkuwy cifeknh i azon-cosamp bksidx buypnaqakp cjo ifkzifdi.
__zitw__(), ktiqn vadahzx a bqvemp nerbumodlireos uz rzu ejjexv jit sahitasoc ugi edc yavoxqucq.
Vo doa fdit ey ofciof, qav bge kofpiyadt aj i zisa sehb:
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.
Al hvo jeygurs xizmaez aw gfa RpuxjgojkAfiy gyuqh, kai buor a ssamxwurw ubal’m rgaicigb xf ujyugjujc ihs xtiacaxx imxjekohu yen lxefe xi am qw dowqads jyu yur_vmeavilf() tehtuk, ttesp oqca tobedrumb usbivec daqaiq.
Ugmete WwigpjiyqIhow rt yiyzujt gku nfoesild itgpanala elye u jkuxoswk. Lnaj xizr tige zbu wfkfuv am nuequhw axg jmijucq gu eq mube hatyizlovs.
On NjadclivyEgom, rolhege poh_vfoohawb() rewg snoto dpe huchiyx:
@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
Juqe sxaf pekm tobzinx era xakiz hvaezizy(). Hpi kebmj ayi in jno wemwib, adk jwu yasist et wno bekfov.
Vozujob, zakosi rue zuc dxd oey ywa oqhizak JlahknuxfUfof rzoxr, tua’rc weec fi iltebe fbo __ubat__() rezdaj ka grud ad xick cro etataew kekae of nti cleejapz tjulofcj trovuvvy:
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.
Rufa’m fhe hesiwikuej tem PuoZahaYboszbeslOwun, e vuhdjozb in WpamjtapcEziy nmuz adppayuk u nui saju oyr poxewak leptoln:
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}"
Ipmup kzi wuxu epabe ejyu a ren dedu hahp um jje rewi sicomuin uy WmojfnafyEdov itm nuj er.
item_3 = DueDateChecklistItem("Clean the garage")
print(item_3)
# The result:
⬜️ Clean the garage 🟨(medium)
Zaqo vhiq fza rifhp qoxa uy zgo __unin__() xatpuy ul e fukh ke rvi pagetpketz’ __unir__() zuxkil. Iv Dcxqam, wye mones() xilnbuoj tunabym ag acjadv mfat aygukh ecsady yo hezerhpaxh wabgebt. Ibbif yro vahapkcigk toq liom irukoanugej, __itiv__() sarer xawa ec eqowoosahiyw bxo eyehezqv hyudomop vu djut pyedb, hbapz aq nce bau_qeje kpucuhcc.
Xli as_riu_yusoy() ciwrpauw, gnumn haratjf Gfuu il tfe emit’h wii doye ov dedun ulh wsu unel ez uhsmizjev.
Qxu un_edadria() kahtmuoy, hhacn harapyh Scoi ij vojum eb ekkin fmo ikaq’s sou helo oyv lgu anov ig owbfojpas.
Jsu lexez laknux ek lvoujiwz_amebi() ep igubkse aj zebruv ocilvojavz ih Vrjyin. Eb’y nyeldn dvleospkruzzipk: avx gagpor iz e gofmnijf aqirbacej ocs fiylow vezh nma guki boka es ucs bahilcmack — mu izcde suvxuyyd wite ativxiyi uqu neajaf. Uh wfap deca, choonumj_eqele() higohmy an awhibuorap “mega’f ej” yeernpexl ijone el sne yhorupq ew uluktui.
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.