Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
pyohio magic methods
Search
Sponsored
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
darshan
July 25, 2019
65
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
pyohio magic methods
Slides for my presentation at PyOhio 2019.
darshan
July 25, 2019
More Decks by darshan
See All by darshan
Magic Of Python
dmark11235
0
65
Featured
See All Featured
Bioeconomy Workshop: Dr. Julius Ecuru, Opportunities for a Bioeconomy in West Africa
akademiya2063
PRO
1
410
実際に使うSQLの書き方 徹底解説 / pgcon21j-tutorial
soudai
PRO
203
77k
SEO Brein meetup: CTRL+C is not how to scale international SEO
lindahogenes
2
2.9k
The Language of Interfaces
destraynor
162
27k
ReactJS: Keep Simple. Everything can be a component!
pedronauck
666
130k
How to train your dragon (web standard)
notwaldorf
96
6.9k
How People are Using Generative and Agentic AI to Supercharge Their Products, Projects, Services and Value Streams Today
helenjbeal
2
360
Leadership Guide Workshop - DevTernity 2021
reverentgeek
1
400
Navigating the Design Leadership Dip - Product Design Week Design Leaders+ Conference 2024
apolaine
2
480
The agentic SEO stack - context over prompts
schlessera
0
970
Agile that works and the tools we love
rasmusluckow
331
22k
Leveraging LLMs for student feedback in introductory data science courses - posit::conf(2025)
minecr
1
440
Transcript
Magic of Python Darshan Markandaiah 1
Agenda 2
Magic Methods? 3
class User: def __init__(self, user_name): self.user_name = user_name 4
Groups of Magic Methods 4 Define Custom Behaviour 4 Enable
Operator Overloading 4 Emulate Built in types 5
Sample Code class Cart: def __init__(self, user_id): self.user_id = user_id
# mapping of item_name -> Item object self.cart_items = dict() def add_item(self, name): self.cart_items[name] = Item(name) class Item: def __init__(self, name): self.name = name 6
>>> cart_1 = Cart("user_id_1") >>> cart_1.add_item("milk") >>> print(cart_1) <__main__.Cart object
at 0x10c7f6ef0> >>> print(cart_1.cart_items) {'milk': <__main__.Item object at 0x10944b940>} 7
Define Custom Behavior Define Custom Behavior 8
__repr__ Define Custom Behavior 9
class Cart: . . def __repr_(self): return f"Cart('{self.user_id}')" . .
Define Custom Behavior 10
>>> cart_1 = Cart("user_id_1") >>> cart_1.add_item("milk") >>> print(cart_1) Cart('user_id_1') >>>
"String Formatting: {0}".format(cart_1) 'String Formatting: Cart of (user_id_1)' Define Custom Behavior 11
__bool__ Define Custom Behavior 12
class Cart: . . def __bool__(self): return len(self.cart_items) > 0
. . Define Custom Behavior 13
>>> cart_1 = Cart("user_id_1") >>> cart_1.add_item("milk") >>> if cart_1: print("Cart
contains at least 1 item.") else: print("Cart is empty.") "Cart contains at least 1 item." Define Custom Behavior 14
Method Invocation __hash__ hash(object) __str__ str(object) __del__ del object* Define
Custom Behavior; *: called when reference count reaches 0 15
Enable Operator Overloading Enable Operator Overloading 16
__gt__ Enable Operator Overloading 17
class Cart: . . def __gt__(self, other): return len(self.cart_items) >
len(other.cart_items) . . Enable Operator Overloading 18
>>> cart_1 = Cart("user_id_1") >>> cart_2 = Cart("user_id_2") >>> cart_1.add_item("milk")
>>> cart_2.add_item("milk") >>> cart_1 > cart_2 False >>> cart_1.add_item("eggs") >>> cart_1 > cart_2 True Enable Operator Overloading 19
Other Comparison Methods Method Invocation __ge__ self >= other __lt__
self < other __le__ self <= other __eq__ self == other __ne__ self != other Enable Operator Overloading 20
@functools.total_ordering Enable Operator Overloading 21
import functools @functools.total_ordering class Cart: . . def __gt__(self, other):
return len(self.cart_items) > len(other.cart_items) def __eq__(self, other): return len(self.cart_items) == len(other.cart_items) . . Enable Operator Overloading 22
>>> cart_1 = Cart("user_id_1") >>> cart_2 = Cart("user_id_2") >>> cart_1.add_item("milk")
>>> cart_2.add_item("milk") >>> cart_1 < cart_2 False >>> cart_1 >= cart_2 True Enable Operator Overloading 23
__add__ Enable Operator Overloading 24
class Cart: . . def __add__(self, other): new_cart = Cart(self.user_id)
for item in self.cart_items: new_cart.add_item(item) for item in other.cart_items: new_cart.add_item(item) return new_cart . . Enable Operator Overloading 25
>>> cart_1 = Cart("user_id_1") >>> cart_2 = Cart("user_id_2") >>> cart_1.add_item("milk")
>>> cart_2.add_item("eggs") >>> cart_3 = cart_1 + cart_2 >>> for item in cart_3.cart_items: print(item) 'milk' 'eggs' Enable Operator Overloading 26
Other arithmatic magic methods Method Invocation __sub__ self - other
__mul__ self * other __div__ self / other __pow__ self ** other Enable Operator Overloading 27
Reflected numerical magic methods Method Invocation __radd__ other + self
__rsub__ other - self __rmul__ other * self __rdiv__ other / self __rpow__ other ** self Enable Operator Overloading 28
Unary Operations Method Invocation __abs__ abs(self) __neg__ -self __pos__ +self
Enable Operator Overloading 29
and others found in the documentation... Enable Operator Overloading 30
Emulate Container Types Emulate Container Types 31
__len__ Emulate Container Types 32
class Cart: . . def __len__(self): return len(self.cart_items) . .
Define Custom Behavior 33
>>> cart_1 = Cart("user_id_1") >>> cart_1.add_item("milk") >>> cart_1.add_item("eggs") >>> len(cart_1)
2 Define Custom Behavior 34
__contains__ Emulate Container Types 35
class Cart: . . def __contains__(self, key): return key in
self.cart_items . . Emulate Container Types 36
>>> cart_1 = Cart("user_id_1") >>> cart_1.add_item("milk") >>> cart_1.add_item("eggs") >>> print("eggs"
in cart_1) True >>> print("cheese" in cart_1) False Emulate Container Types 37
__iter__ Emulate Container Types 38
class Cart: . . def __iter__(self): for item in self.cart_items:
yield item . . Emulate Container Types 39
>>> cart_1 = Cart("user_id_1") >>> cart_1.add_item("milk") >>> cart_1.add_item("eggs") >>> for
item in cart_1: print(item) 'milk' 'eggs' Emulate Container Types 40
__getitem__ Emulate Container Types 41
class Cart: . . def __getitem__(self, key): return self.cart_items[key] .
. Emulate Container Types 42
cart_1 = Cart("user_id_1") cart_1.add_item("milk") cart_1.add_item("eggs") cart_1["milk"] Item(milk) Emulate Container Types
43
Related Magic Methods Method Name Similar __setitem__ self[key] = value
__delitem__ del(self[key]) Emulate Container Types 44
and others found in the documentation... 45
collections.abc 46
Use Case: Checking for interfaces 47
>>> from collections import abc >>> isinstance(list(), abc.Sequence) True >>>
isinstance(dict(), abc.Mapping) True >>> isinstance(list(), abc.Hashable) False >>> isinstance(str(), abc.Hashable) True 48
Use Case: Offer Free Mixin Methods 49
from collections import abc class Cart(abc.Mapping): . . def __iter__(self):
for key in self.cart_items: yield key def __len__(self): return len(self.cart_items) def __getitem__(self, key): return self.cart_items[key] . . 50
>>> cart_1 = Cart("user_id_1") >>> cart_1.add_item("milk") >>> cart_1.add_item("eggs") >>> list(cart_1.values())
[Item(milk), Item(eggs)] >>> print('milk' in cart_1) True 51
other ABCs that offer free mixin methods 52
Context Managers 53
file_handle = open("/path/to/file") try: content = file_handle.read() finally: file_handle.close() with
open("/path/to/file") as file_handle: content = file_handle.read() 54
Defining your own Context Managers 4 __enter__ 4 __exit__ 55
class FileReader: def __init__(self, filename): self.filename = filename def __enter__(self):
self.file_handle = open(self.filename) return self.file_handle def __exit__(self, exc_type, exc_value, traceback): if self.file_handle: self.file_handle.close() with FileReader("/path/to/file") as file_handle: content = file_handle.read() 56
@contextlib.contextmanager 57
Resources 4 Python Data Model Documentation 4 Python collections module
documentation 4 A guide to Python's Magic Methods 58
Thank You! 59