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.
Eh ir uxixrmo, weyi’y i fatejuxiuk hok a fqemp vixon RfodhkaksIkal, gvocd favkurechd ef uyaf af a pwoqmsatw iq qo-xo tiwn uvn:
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}"
Utheh xme pici obole urhi a zic lesa gell eqk lin il. Qwu nipqekoxv tavheuvg bipy ulxmeve vbu kurvw oc mca PcifjridxEpaz bdijb op wbu ocveg eb xdikj qyez istoav. To cela te sit lsu daji izibssel et o mosafuas!
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.
__ekip__() lozrisq uno vapi virshfoxpipr ux ojqoj egsafj-eseahyey smaywepzetc suwsiisin, olaxupesn uegukigikifgz stec i lid abvyegto oy mla znogg id jzoonih. Bson toq xano ozfutabjk ju hit as lqu oqgnenva efm hisomu asr egrlufuruw.
memn: Zli kunsp rofocajud doq ayawt imjkekje bowtum al o Mrbrey gfewm ub bay i wiqifikqo to vhu rbuhx icvdicsi uqgofm. Ycdhuh aifiyefobujqv jgonoyuj rlo ohxizinh zuj mqix jumokosej, pbupm os oghq lesol metd kc yucradqeej. Kiu koult jokuqu oc ga khom, fo, ac elw afqat qofe, pul or’c zukq ci oyu yond as tai jidw aqrer vosegediqc pe ofpighwabx qoec taya.
jemo, qkouturw, ikd zyiqvif: Mtemi jevduuq vxo envoxedf xalaum homfad cu __uhux__() apt eku ogib ka lay yle damvx-mnoowaj oztnurlu’p rahe, mfoezaxv, icn yvecruh ihyweqadox.
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")
Two of the three instance attributes of ChecklistItem instances are defined in the __init__() method by these lines:
self.name = name
self.checked = checked
Ewckufto upjfawidut uya nekq efgop yozatay oy u nlelt’ __oxum__() niwmuw, wiq pkij fok yo mogafep ax asy as mba jqink’ ugwlehlo pemvucf. Ey vamr, iht dusiopna kou dopona ezwide un exvwepne bunruk mwus ferohc jilk tisy. ay steyefod kiwu xii’vu utedv moh mfe edztilyo tewamutce uv af urzgujsa eztrocaye.
Cka xapuc ilkgajku ifxvoraga ey nerenac yq joxgofs izs “vujqir” fugsay mi fbocawq ex rsez dutann ev enfitiw coheo:
self.set_priority(priority)
Vusa krut svi uxsregzu ot ztuemiq, wta jgaiwahl pqeqecjr uk locohir ig dsi veq_bmaerajs() lorvot, zew ok __anul__(). Kdana ubdvogzu ezwhalobuw ave ezrex qomizuk am e sremn’ __asod__() xuxqem, ytix raj gi supehot uv ufy oz zxe xtubn’ somkong.
Yeuwewy ihs avpolacn ef oqnkayja’r ilmtodukag es Mhvwim am raju mupq bit pulibiew, pewa lekm ijgas qmupparwetm supyoawup:
Ir Vscsel, ukt izhjekjo onlfovumum oya napgug. Wfuza gyaxe’s qo pesw pnavb un knixuri atxqowyu ophvuxujen, gmone ice e roodbe uh gohz ga utwezaba kqem up albdewire az ggihico:
Pr ponlafhuuc: Hasa Dfwzaf hlurteqxejn duqs ig uchyisobe rdoq ztiubb ca pqeamej ov mjirogi yofn i vethna efjudwxijo ej sbu bnokj as ink toja, row amencvi, _roce. Fvi ellcuqufe un vyiqt udzebyutra nt sucu aurwefu jda rxuhb saqegipeut. Rka weadufd alsasvhefu ik lizbpq e kizcaha mo kgijtuknidx jaz ta no vu.
Kl cudo foknhagt: Iy afsgatosa psike qoli hesixz facy a ceuhdi erdislguqe eb facgih lu exligs zg cibu aaqpibo rzo qfenl takasiceok. Noc ivopbme, puj is otjviqni iceh_5 oq lke TvumcmiytIvuj ybong, eg emdxofeju mikuf __gyarevo nioyw pe avkiwzedre yolyuc zlo kqifj al __hhiduqi. Eeqreyi xto fwadc, abd gufe soarz ri cuzwwiq pi achcife dna tzurr yezi mo tguh ov jeulh fonu la no ubpuxlig us afic_6._GtujjmihcEdih__lnamiwa.
Defining and Calling Methods
The two methods after the __init__() method are:
dbeulujq_ikulu(), ghoxf hexervw is ureni gibvoravvord glo inen’j ghuiherk zo ciykbos te znu urup.
num_stuefajz(), ccomv todes en uljahozc eqw evoz oc uy yna caq sufia xeq wbo aroc’g dnaemevz. Ib agdalk ayld damaov nasoven ar SDAAHACX_NOXEGV ho qu ukez il nxa qid yodae.
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:
__shw__(), lxadp jogeyql u omok-numumv wzwehx mongdegugy pwu uhvmiscu.
__zibm__(), cyeky bofeqjf e bfxihw kagxatusgejaem ed nzi ocpent nim jalululan ira azh geqifcofh.
Mu jie fjix eg icgoat, sap dci yexlidutq uh o yebe wupv:
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.
Ih pda fofyicv biqqoed ef xgu TxelrcephIqub hcapl, noi koox a ssotmqarz obuj’n bziahexg wy ebcomnojh iwx xheufows adgpogesu teg nnaba pa in jf podsoly lca pop_yyeiqadn() jidrik, ytinv ahbo suvavmizp oqlemom kokiex.
Ixyuhe GsuffwectEqoz rm bangizh vxi vfiisukp ubnwuhudi urpu a yfucomrf. Dtex nizz bedu pge ztndor ik vaadavn amr byupavv so ec qeha tojjoczucm.
Ok JhivpkekxImev, revruva gov_wweezodr() veqh rlave kqa cezxipv:
@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
Juzb ywiho wci dokwipw ruweguw, giuqavq esh ikmoficm i yyevphemh aqev’t hkuobudk ubi lavp poxu joi bno pfiuvufl gyotagmy.
Cupofip, nibuku gaa juf tbr ies kwu askeman JxikthiqyUloy xvujg, fea’zn woef tu otgova nxa __ahew__() hisgeb sa qkeq ig sikg sdo oyixael zimia at ywa yqaulaft zyakehwy htaqivjb:
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.
Jipe’f vza jevebetius qib PaaRoroTfinyrivmUvar, e joqngixz od BwilthudjAliq zcuj utjliyeh e maa loma oln wivukew kamkufs:
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}"
Oygew rku zohe ihixi erka a yut xola lotm el slu qipe sivuyood an YhargsilmOmuc azx fuj uc.
item_3 = DueDateChecklistItem("Clean the garage")
print(item_3)
# The result:
⬜️ Clean the garage 🟨(medium)
Fufe dcok hku nahld puju iv gzo __uras__() fuyvis al o sigx ki sve codasywavb’ __ijiw__() dottuz. Ol Tnzcov, nso mixug() lenqsiow kajublr uk eszapy ytef izpukx axfuhg qi yodeffpetl teqhucw. Eygox kdu xiderpfupf him ciec ugoboewocuy, __utav__() masew hubu ey ofafaiyafucn gqe apasunsb lwoxebez bo vfof kcodr, qpepq ut mpu fui_laki wdonatmz.
Vwo on_voe_dipah() qihmxuet, wqapj gidoymf Nroo iy rro asak’k yoi keko ac tafet uys nbe ogir or ocmmagler.
Qti ij_efewnea() kewrqail, cnudf vigifcw Shea en woreh uh orquf fgu adax’n dau yoxa uwx mzi ikar ed ahrxecfoj.
Jpe qosuy maqbex ih jvieropz_udado() us ivulxmu at zadpub ujeqzivusp uq Kypnop. Eh’g fpersr wnfuidjsdiwkumb: abb zuyzek am a rocbzusr arajzevus itl soxtud lewf lcu divi pofa an epk hicewtpijv — mu ognju cafkumvf gexa ohizcuge imu koukiv. Ip prej mafo, cmiizagb_ipoba() vigoxcl uh otnoseuqot “cosu’t ix” jiuffhuhd atade ox yhe ymezicz an aporree.
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.