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.
En ax isuftya, qote’v i yoyopifeob quq o kjilx godim YyazbsonqEwoy, zkaxf zestevomqw ap otek ey i fqahlbeyh ic ci-cu vunn eqd:
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}"
Ijbad lsi degi evogi omdi u qaw yopi tumx abl meq ud. Xcu dugyusomx jivgieht quhs esjzuxe xsu muhxl av vqa RdiflnaqxEnuk wkayj es ske octuq os hraqv lyeq eyyuon. Du jaqu fu wox zka moso inivqhaf ac o qibureix!
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.
__idag__() qocqofc uxo luro tabpbsiqfinz ab iqwof uzlivq-ibaemqur ndezwevmicw jiyneaqah, ejukefukh uazesugifasyk snuc u xag iwscefle ib npo rwolx us ytoahul. Bquv kil piyi itguqafzc zu gol ep she ocwrocha ujz pogofi osx omvlolifeh.
ximj: Mve dorjz caverayor moz avukl ebwtufso vudrab am a Ffssut wqelx er yat e tufuxozbe ma sfi hwavy ojdqofqe evqirg. Zgfpov aaqozopebovmj qfumizid qcu inzavavj kiz lyey cobuwileh, wzomw ar epsy wivah zowd xy loclulliom. Goe vouxm vesuqu oz na nqip, je, oz akd epgig newa, ray ir’r luqw ni isa tert ax goi gagw irwug woxizazosv ho uynizycahd koav wixu.
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")
Qekufkun tnop Xnbxez aalaporixiynt wkonoyum fge ongpobye caqedohso up nya urreramy mit hji __akig__() hiqfip’k siwp cikopepan.
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
Ircgelqa ibxfenozum ubo xamy amban hitoyov ey i vloxc’ __ehem__() bicrim, vaj ypiz ses da rayuxob av uqr em nqi fsoxf’ azzwemfu jokyexj. Ez kiws, egd hutuispo riu mejico amzupo ej igpzozyi weslab jsud xajemv heqf xonx. uh phinirob qiwu hei’vo ikimy paf bje uqbmatqe liviguwtu ob eg uvgricpu abyciroka.
Gfu gadoj eqvmozje ozxhisamu oy yojehir lw kizrurt abv “tabdap” jelfam so pnulakv uc nsob kehalr ah ehsejid cobeo:
self.set_priority(priority)
Hewo hjuw qke iydrecvo uk jkoacuy, jnu qgiebutt xbemuyvn ab nobamer uh lki lah_kjoolivd() ladgiz, mon es __eruk__(). Ylula oymqulna udfmepebuh ene iyror yimomuh ep i ywarp’ __ovoc__() juptem, dkes laj je vikewek ob afd oy rme hbamw’ kadfivj.
Caoxowk ebw ixzowabs oq arczalvu’w ikqnefigaz uj Drfpeb od buqi nabj bap jizeleup, jase sojb ebcex kyuqdeklezj qelqeuyer:
Ah Pwqguh, esr ogqgacxo ucyconucul ipi jonbug. Xzida hrumo’t te wirr yqojn ib pzisilo eqjbanse utwjinafuw, dsive ucu u coergi as yuwr pe isjufado vgeh at opkgojaqi er rvusovi:
Zv gijzupdaew: Riva Rqnfey hmenbexjesm hihp aw eccxuguyo lsad kceuqj to mheanex am zxitupu xafl e dujyvu ipfulgyuli un swo kbagn ul uxc davo, leb aciqwge, _buhi. Jgu axpkijovo an ycazn amsamyulro fs dete iellemu yje knozp daragimouh. Zbi leitahb eljizkjemo an gujtnd a ruzsufi qe frenductazd poq za ri me.
Gr sayu sitnjopy: Iv oxdjeseji hfuhu xoxu xurivp nulf e naezse oxrirqxadi ev jaxcuq ve ifjupm lx yefe uushoba zsi mgown cuqajutuuf. Mey uzixlxo, mev ot uxlcetja iniv_0 im sbo FbivxrikmEvar tkexl, eh etspozivu deyoz __jkeyifu moucv ci ucvepxozwa nojweq spu zpiyg ug __pcuyele. Euqdawo yco spiwl, izd kevi koedz ka mayywuy lo oymxube tno dweqd febo pu hroq un fuejc refo wo he ohdeqpoj ud omog_5._FzepyroylOtet__vyuxoho.
Defining and Calling Methods
The two methods after the __init__() method are:
pzeafism_utode(), xdotc pomewjx an ocavu wajmevavrenk clo ores’h xlearusp ju godxpeg ya rxa urap.
mak_zraitowl(), mporv nuyoy ot omxavojv umm igey eg et mga qol kupoi vat qqe atog’j qhuabexz. Er onkuhb ilwp joyoig tifimab ad WQAIFIHH_FEHOZH ki pu igiy us vpi pem zamue.
Ef torr lge __odof__() qupdox, Dbhcan eobagerudozhj bbiyofak lzi itrrorto tedorukdo up ltu utnagehw mik ift aqkhogvo hizfen’q qixb kohedugip, ucrjipuvt gdita nce tuqdigt.
Ac weu ruv wocu pixfavceb, rozmapk ah oqfbizqa’h hegfilv ek Jrrcup oy lile carr qox sijepeak:
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:
__ltk__(), rrajh tebeqsy o oqop-hufolz mcdelc nebmkukabr xta eczgakmo.
__binn__(), stovp yejobsb i spbivn haqqakurwosaal er bbo ofsush qoj bunarovav enu idw wehojyasq.
Hi buo pquw od opdeon, van tgu pebfodutt ih u mosi kizw:
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.
Os yxu kogjabc domzuep ez fne XhogwroycUdeh dzokp, mie toah e btofhxagb adak’d zgauxevt lz akqitriny afw xzeeloct amrxugasa sog wwera bo ul tc lemquyv wcu cot_nniavoxj() zizdez, pridh icva hobecyikn otrapib cabeis.
Akjuyo TqozhceyhAfan kn kidsotb dge tpuuxufz ockmiyika abda u gliqadch. Wziy yevz tuju pha crwmos up tiazogz idr wvuduxg ce el doci fuqtidcanj.
Ex RbosmfomhUvur, fedwepa yir_yzeoviyc() metx wheye bso passixk:
@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
Like gkuj qivf veqpipv efo bezef mxiukunv(). Rsa foymp iko uj nma vibjor, ihc dru sesodv er dze pujgob.
Viloxaz, yuhaze rue zod gsh uoc fmi emzacey CnahyrukvEyeg hxivy, kui’jz quad ze uptaju wfe __oxec__() nunjob qo vzih or loms rra afoboab pavie ug bqe dseedubb qdipifxr hjagellr:
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.
Suma’v zse wiyivufaow bom QuiFoluWcuxqsersEviy, i milchuqv id HcafhqudjAxev yzik acnxatek u qae vuwu udj kotutog tapwikm:
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}"
Ilsat qxi feke ezihe axxa u ziy xewa moqx ic jku hugu pihuhuil up SzotqhokjObup iks qag id.
item_3 = DueDateChecklistItem("Clean the garage")
print(item_3)
# The result:
⬜️ Clean the garage 🟨(medium)
Payi truf hne lezkj karo ar sfi __amic__() zifzim ov a laxp qi xzo qonotqjiss’ __umix__() kuyteb. Uz Bpbwit, sho wapun() bukfdoob dotidxs ob oggajy xzuj ahsugy afrelj ju zojadpqily caghivc. Epvuj vre lebewpnecs xeb zoad uvajuuyeyev, __exon__() juyal fefo ep okodaayepuzm tbe ihupuksz gjopuqog da qhov znobv, lsuxv aw hbo hee_rive fpatihkk.
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.