SlideShare a Scribd company logo
Python's Magic
Methods
Reuven M. Lerner, PhD • reuven@lerner.co.il
http://lerner.co.il/
1
Methods
• We define methods on a class
• We then invoke them via an instance
• (We're going to ignore static and class methods)
• The method is found via attribute lookup:
• Object -> object's class -> super -> … -> object
Method naming
• We can use whatever method names we want!
• So long as we take "self" as a parameter, Python
doesn't really dictate the names that we use
Except.
• Except for the so-called "magic methods"
• These methods are rarely called directly!
• Rather, they're called automatically by Python,
typically as the result of invoking an operator
__init__
• __init__ is the first method that many Python
programmers learn about.
• It's not really a constructor, since the new object
already exists when __init__ is invoked.
__len__
• When you call len(x), it looks for __len__
• Don't call __len__ directly; rather use len()
• You can, of course, return whatever you want,
which is the point — whatever is appropriate for
your object
Example
class Book(object):
def __init__(self, title, author, num_pages):
self.title = title
self.author = author
self.num_pages = num_pages
def __len__(self):
return self.num_pages
>>> b = Book('The Terrible Two', 'Mac Barnett', 224)
>>> len(b)
224
Really magic methods
• Most people who learn about Python object learn
about __init__, __len__, and probably __repr__ and
__str__.
• But the magic methods go way beyond that!
__add__
• Add two elements together
• __add__ gets two parameters
• self
• Another object
• How do you add them? That's up to you!
• Typically, you'll return a new instance of the same
class
Example
class Foo(object):
def __init__(self, x):
self.x = x
def __add__(self, other):
return Foo(self.x + other.x)
def __repr__(self):
return "Instance of f, x = {}".format(self.x)
f1 = Foo(10)
f2 = Foo(20)
print(f1 + f2)
__iadd__
• We can also address what happens when += is
invoked
• This is not the same as __add__!
• The expectation is that you'll change the state of
the current object, and then return self.
Example
class Foo(object):
def __init__(self, x):
self.x = x
def __iadd__(self, other):
self.x += other.x
return self
def __repr__(self):
return "Instance of f, x = {}".format(self.x)
f1 = Foo(10)
f2 = Foo(20)
f1 += f2
print("Now f1 = {}".format(f1))
Making __add__ flexible
• Remember, the second argument can be anything
• If we want, we can play games with that —
checking for attributes
Example
class Foo(object):
def __init__(self, x):
self.x = x
def __add__(self, other):
if hasattr(other, 'x'):
return Foo(self.x + other.x)
else:
return Foo(self.x + other)
def __repr__(self):
return "Instance of f, x = {}".format(self.x)
f1 = Foo(10)
f2 = Foo(20)
print("f1 + f2 = {}".format(f1 + f2))
print("f1 + 10 = {}".format(f1 + 50))
Reversible?
• What if we now say
print("10 + f1 = {}".format(50 + f1))
• What will Python do?
f1 + 10 = Instance of f, x = 60
Traceback (most recent call last):
File "./foo.py", line 29, in <module>
print("10 + f1 = {}".format(50 + f1))
TypeError: unsupported operand type(s) for
+: 'int' and 'Foo'
__radd__
• Auto-reversing: We get self and other, and now
invoke our previously defined __add__:
def __radd__(self, other):
return self.__add__(other)
How does this work?
• Python tries to do it the usual way
• It gets NotImplemented back
• Not an exception!
• An instance of Not ImplementedType!
• Python then tries (in desperation) to turn things
around… and thus, __radd__
Type conversions
• You probably know about __str__ already
• But what about __int__? Or even __hex__?
Example
def __int__(self):
return int(self.x)
def __hex__(self):
return hex(int(self.x))
Boolean conversions
• Your object will always be considered True in a
boolean context, unless you define __nonzero__
(__bool__ in Python 3)
Example
class Foo(object):
pass
f = Foo()
>>> bool(f)
True
But with __nonzero__…
class Foo(object):
def __init__(self, x):
self.x = x
def __nonzero__(self):
return bool(self.x)
>>> f = Foo(1)
>>> bool(f)
True
>>> f = Foo(0)
>>> bool(f)
False
Format
• Originally, Python used the % syntax for pseudo-
interpolation:
name = 'Reuven'
print('Hello %s' % name)
• But there are lots of problems with it, so it's better
to use str.format
str.format
name = 'Reuven'
print('Hello {0}'.format(name))
Pad it!
name = 'Reuven'
print('Hello, {0:20}!'.format(name))
Move right
print('Hello, {0:>20}!'.format(name))
Custom formats
• It turns out that our objects can also handle these
custom formats!
• If we define __format__ on our object, then it'll get
the format code (i.e., whatever comes after the :)
• We can then decide what to do with it
class Person(object):
def __init__(self, given, family):
self.given = given
self.family = family
def __format__(self, format):
if format == 'familyfirst':
return "{} {}".format(self.family, self.given)
elif format == 'givenfirst':
return "{} {}".format(self.given, self.family)
else:
return "BAD FORMAT CODE"
Using it
>>> p = Person('Reuven', 'Lerner')
>>> "Hello, {}".format(p)
'Hello, BAD FORMAT CODE'
>>> "Hello, {:familyfirst}".format(p)
'Hello, Lerner Reuven'
>>> "Hello, {:givenfirst}".format(p)
'Hello, Reuven Lerner'
Pickle
• Pickle allows you to serialize, or marshall objects
• You can then store them to disk, or send them on
the network
• Pickle works with most built-in Python data types,
and classes built on those types
Pickling simple data
import pickle
d = {'a':1, 'b':2}
p = pickle.dumps(d)
new_d = pickle.loads(p)
Custom pickling
• Define some magic methods (of course) to
customize your pickling:
• __getstate__ returns a dictionary that should reflect
the object. Want to add to (or remove from) what is
being pickled? Just modify a copy of self.__dict__
and return it!
• Don't modify the dictionary itself…
Example
class Foo(object):
def __init__(self, x):
self.x = x
def __getstate__(self):
odict = self.__dict__.copy()
odict['y'] = self.x * 2
return odict
>>> f = Foo(10)
>>> p = pickle.dumps(f)
>>> new_f = pickle.loads(p)
>>> vars(new_f)
{'x': 10, 'y': 20}
Equality
• What makes two object equal?
• By default in Python, they're only equal if their ids
are equal
• (Yes, every object has a unique ID number — use
the "id" function to find it!)
• You change this by defining __eq__!
Changing equality
class Foo(object):
def __init__(self, x):
self.x = x
def __eq__(self, other):
return self.x == other.x
>>> f1 = Foo(10)
>>> f2 = Foo(10)
>>> f1 == f2
True
Hashing
• If two objects are equal, then maybe they should
hash to the same value, right?
• We can set the __hash__ attribute to be a method
that returns whatever we want
Playing with __hash__
class Foo(object):
def __init__(self, x):
self.x = x
def __hash__(self):
return hash(self.x)
>>> f = Foo('a')
>>> hash(f)
12416037344
>>> hash('a')
12416037344
f = Foo(1)
>>> hash(f)
1
Messing around with
hashing
• What if we have __hash__ return a random number
each time?
• That will have some interesting consequences…
Questions?
• Follow me: @reuvenmlerner
• Buy my book, "Practice Makes Python"
• 10% off with offer code "webinar"
• Get my newsletter: http://lerner.co.il/newsletter
• Read my blog: http://blog.lerner.co.il/
• Learn a bit: http://DailyTechVideo.com/

More Related Content

What's hot

Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
Damian T. Gordon
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
Python - object oriented
Python - object orientedPython - object oriented
Python - object oriented
Learnbay Datascience
 
Advanced Python : Decorators
Advanced Python : DecoratorsAdvanced Python : Decorators
Advanced Python : Decorators
Bhanwar Singh Meena
 
Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods
Bhanwar Singh Meena
 
What Are Python Modules? Edureka
What Are Python Modules? EdurekaWhat Are Python Modules? Edureka
What Are Python Modules? Edureka
Edureka!
 
Python : Functions
Python : FunctionsPython : Functions
Python : Data Types
Python : Data TypesPython : Data Types
Python: Polymorphism
Python: PolymorphismPython: Polymorphism
Python: Polymorphism
Damian T. Gordon
 
Python 101 1
Python 101   1Python 101   1
Python 101 1
Iccha Sethi
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
Sujith Kumar
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
Srinivas Narasegouda
 
python Function
python Function python Function
python Function
Ronak Rathi
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
Mayank Bhatt
 
F strings
F stringsF strings
F strings
Mariatta Wijaya
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
Kamal Acharya
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
Emertxe Information Technologies Pvt Ltd
 

What's hot (20)

Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Python - object oriented
Python - object orientedPython - object oriented
Python - object oriented
 
Advanced Python : Decorators
Advanced Python : DecoratorsAdvanced Python : Decorators
Advanced Python : Decorators
 
Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods
 
What Are Python Modules? Edureka
What Are Python Modules? EdurekaWhat Are Python Modules? Edureka
What Are Python Modules? Edureka
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Python: Polymorphism
Python: PolymorphismPython: Polymorphism
Python: Polymorphism
 
Python 101 1
Python 101   1Python 101   1
Python 101 1
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
 
python Function
python Function python Function
python Function
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
F strings
F stringsF strings
F strings
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
 

Similar to Python's magic methods

Using and Abusing Magic methods in Python
Using and Abusing Magic methods in PythonUsing and Abusing Magic methods in Python
Using and Abusing Magic methods in Python
Slater Victoroff
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
muneshwarbisen1
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
Francesco Bruni
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
Jim Roepcke
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonTendayi Mawushe
 
Scala: A brief tutorial
Scala: A brief tutorialScala: A brief tutorial
Scala: A brief tutorial
Oliver Szymanski
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python ClassJim Yeh
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)
Rick Copeland
 
Object_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfObject_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdf
Koteswari Kasireddy
 
Code Like Pythonista
Code Like PythonistaCode Like Pythonista
Code Like Pythonista
Chiyoung Song
 
Descriptor Protocol
Descriptor ProtocolDescriptor Protocol
Descriptor Protocolrocketcircus
 
Descriptor Protocol
Descriptor ProtocolDescriptor Protocol
Descriptor Protocolrocketcircus
 
OOC in python.ppt
OOC in python.pptOOC in python.ppt
OOC in python.ppt
SarathKumarK16
 
08-classes-objects.ppt
08-classes-objects.ppt08-classes-objects.ppt
08-classes-objects.ppt
ssuser419267
 
08-classes-objects.ppt
08-classes-objects.ppt08-classes-objects.ppt
08-classes-objects.ppt
UmooraMinhaji
 
Python - Classes and Objects, Inheritance
Python - Classes and Objects, InheritancePython - Classes and Objects, Inheritance
Python - Classes and Objects, Inheritance
erchetanchudasama
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
Damian T. Gordon
 

Similar to Python's magic methods (20)

Using and Abusing Magic methods in Python
Using and Abusing Magic methods in PythonUsing and Abusing Magic methods in Python
Using and Abusing Magic methods in Python
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in Python
 
Scala: A brief tutorial
Scala: A brief tutorialScala: A brief tutorial
Scala: A brief tutorial
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python Class
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)
 
Object_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfObject_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdf
 
Python classes objects
Python classes objectsPython classes objects
Python classes objects
 
Code Like Pythonista
Code Like PythonistaCode Like Pythonista
Code Like Pythonista
 
Descriptor Protocol
Descriptor ProtocolDescriptor Protocol
Descriptor Protocol
 
Descriptor Protocol
Descriptor ProtocolDescriptor Protocol
Descriptor Protocol
 
OOC in python.ppt
OOC in python.pptOOC in python.ppt
OOC in python.ppt
 
08-classes-objects.ppt
08-classes-objects.ppt08-classes-objects.ppt
08-classes-objects.ppt
 
08-classes-objects.ppt
08-classes-objects.ppt08-classes-objects.ppt
08-classes-objects.ppt
 
Python - Classes and Objects, Inheritance
Python - Classes and Objects, InheritancePython - Classes and Objects, Inheritance
Python - Classes and Objects, Inheritance
 
About Python
About PythonAbout Python
About Python
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
 

More from Reuven Lerner

Technical training business talk.key
Technical training business talk.keyTechnical training business talk.key
Technical training business talk.key
Reuven Lerner
 
Big Data — Your new best friend
Big Data — Your new best friendBig Data — Your new best friend
Big Data — Your new best friend
Reuven Lerner
 
PostgreSQL, your NoSQL database
PostgreSQL, your NoSQL databasePostgreSQL, your NoSQL database
PostgreSQL, your NoSQL database
Reuven Lerner
 
What can Ruby learn from Python (and vice versa)?
What can Ruby learn from Python (and vice versa)?What can Ruby learn from Python (and vice versa)?
What can Ruby learn from Python (and vice versa)?
Reuven Lerner
 
Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014
Reuven Lerner
 
Web APIs: The future of software
Web APIs: The future of softwareWeb APIs: The future of software
Web APIs: The future of software
Reuven Lerner
 
Rails israel 2013
Rails israel 2013Rails israel 2013
Rails israel 2013
Reuven Lerner
 
Intro to cloud computing — MegaCOMM 2013, Jerusalem
Intro to cloud computing — MegaCOMM 2013, JerusalemIntro to cloud computing — MegaCOMM 2013, Jerusalem
Intro to cloud computing — MegaCOMM 2013, Jerusalem
Reuven Lerner
 
PostgreSQL
PostgreSQLPostgreSQL
PostgreSQL
Reuven Lerner
 
Rails traps
Rails trapsRails traps
Rails traps
Reuven Lerner
 
Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...
Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...
Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...
Reuven Lerner
 
Rails development environment talk
Rails development environment talkRails development environment talk
Rails development environment talk
Reuven Lerner
 
Git talk from Open 2011 conference in Israel
Git talk from Open 2011 conference in IsraelGit talk from Open 2011 conference in Israel
Git talk from Open 2011 conference in Israel
Reuven Lerner
 
Dynamic languages, for software craftmanship group
Dynamic languages, for software craftmanship groupDynamic languages, for software craftmanship group
Dynamic languages, for software craftmanship group
Reuven Lerner
 
Modern Web Technologies — Jerusalem Web Professionals, January 2011
Modern Web Technologies — Jerusalem Web Professionals, January 2011Modern Web Technologies — Jerusalem Web Professionals, January 2011
Modern Web Technologies — Jerusalem Web Professionals, January 2011
Reuven Lerner
 
PostgreSQL talk, Database 2011 conference
PostgreSQL talk, Database 2011 conferencePostgreSQL talk, Database 2011 conference
PostgreSQL talk, Database 2011 conference
Reuven Lerner
 
ActiveRecord 2.3
ActiveRecord 2.3ActiveRecord 2.3
ActiveRecord 2.3
Reuven Lerner
 
Ruby objects
Ruby objectsRuby objects
Ruby objects
Reuven Lerner
 
Rails console
Rails consoleRails console
Rails console
Reuven Lerner
 
Rails tools
Rails toolsRails tools
Rails tools
Reuven Lerner
 

More from Reuven Lerner (20)

Technical training business talk.key
Technical training business talk.keyTechnical training business talk.key
Technical training business talk.key
 
Big Data — Your new best friend
Big Data — Your new best friendBig Data — Your new best friend
Big Data — Your new best friend
 
PostgreSQL, your NoSQL database
PostgreSQL, your NoSQL databasePostgreSQL, your NoSQL database
PostgreSQL, your NoSQL database
 
What can Ruby learn from Python (and vice versa)?
What can Ruby learn from Python (and vice versa)?What can Ruby learn from Python (and vice versa)?
What can Ruby learn from Python (and vice versa)?
 
Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014
 
Web APIs: The future of software
Web APIs: The future of softwareWeb APIs: The future of software
Web APIs: The future of software
 
Rails israel 2013
Rails israel 2013Rails israel 2013
Rails israel 2013
 
Intro to cloud computing — MegaCOMM 2013, Jerusalem
Intro to cloud computing — MegaCOMM 2013, JerusalemIntro to cloud computing — MegaCOMM 2013, Jerusalem
Intro to cloud computing — MegaCOMM 2013, Jerusalem
 
PostgreSQL
PostgreSQLPostgreSQL
PostgreSQL
 
Rails traps
Rails trapsRails traps
Rails traps
 
Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...
Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...
Modern Web technologies (and why you should care): Megacomm, Jerusalem, Febru...
 
Rails development environment talk
Rails development environment talkRails development environment talk
Rails development environment talk
 
Git talk from Open 2011 conference in Israel
Git talk from Open 2011 conference in IsraelGit talk from Open 2011 conference in Israel
Git talk from Open 2011 conference in Israel
 
Dynamic languages, for software craftmanship group
Dynamic languages, for software craftmanship groupDynamic languages, for software craftmanship group
Dynamic languages, for software craftmanship group
 
Modern Web Technologies — Jerusalem Web Professionals, January 2011
Modern Web Technologies — Jerusalem Web Professionals, January 2011Modern Web Technologies — Jerusalem Web Professionals, January 2011
Modern Web Technologies — Jerusalem Web Professionals, January 2011
 
PostgreSQL talk, Database 2011 conference
PostgreSQL talk, Database 2011 conferencePostgreSQL talk, Database 2011 conference
PostgreSQL talk, Database 2011 conference
 
ActiveRecord 2.3
ActiveRecord 2.3ActiveRecord 2.3
ActiveRecord 2.3
 
Ruby objects
Ruby objectsRuby objects
Ruby objects
 
Rails console
Rails consoleRails console
Rails console
 
Rails tools
Rails toolsRails tools
Rails tools
 

Recently uploaded

Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 

Recently uploaded (20)

Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 

Python's magic methods

  • 1. Python's Magic Methods Reuven M. Lerner, PhD • reuven@lerner.co.il http://lerner.co.il/ 1
  • 2. Methods • We define methods on a class • We then invoke them via an instance • (We're going to ignore static and class methods) • The method is found via attribute lookup: • Object -> object's class -> super -> … -> object
  • 3. Method naming • We can use whatever method names we want! • So long as we take "self" as a parameter, Python doesn't really dictate the names that we use
  • 4. Except. • Except for the so-called "magic methods" • These methods are rarely called directly! • Rather, they're called automatically by Python, typically as the result of invoking an operator
  • 5. __init__ • __init__ is the first method that many Python programmers learn about. • It's not really a constructor, since the new object already exists when __init__ is invoked.
  • 6. __len__ • When you call len(x), it looks for __len__ • Don't call __len__ directly; rather use len() • You can, of course, return whatever you want, which is the point — whatever is appropriate for your object
  • 7. Example class Book(object): def __init__(self, title, author, num_pages): self.title = title self.author = author self.num_pages = num_pages def __len__(self): return self.num_pages >>> b = Book('The Terrible Two', 'Mac Barnett', 224) >>> len(b) 224
  • 8. Really magic methods • Most people who learn about Python object learn about __init__, __len__, and probably __repr__ and __str__. • But the magic methods go way beyond that!
  • 9. __add__ • Add two elements together • __add__ gets two parameters • self • Another object • How do you add them? That's up to you! • Typically, you'll return a new instance of the same class
  • 10. Example class Foo(object): def __init__(self, x): self.x = x def __add__(self, other): return Foo(self.x + other.x) def __repr__(self): return "Instance of f, x = {}".format(self.x) f1 = Foo(10) f2 = Foo(20) print(f1 + f2)
  • 11. __iadd__ • We can also address what happens when += is invoked • This is not the same as __add__! • The expectation is that you'll change the state of the current object, and then return self.
  • 12. Example class Foo(object): def __init__(self, x): self.x = x def __iadd__(self, other): self.x += other.x return self def __repr__(self): return "Instance of f, x = {}".format(self.x) f1 = Foo(10) f2 = Foo(20) f1 += f2 print("Now f1 = {}".format(f1))
  • 13. Making __add__ flexible • Remember, the second argument can be anything • If we want, we can play games with that — checking for attributes
  • 14. Example class Foo(object): def __init__(self, x): self.x = x def __add__(self, other): if hasattr(other, 'x'): return Foo(self.x + other.x) else: return Foo(self.x + other) def __repr__(self): return "Instance of f, x = {}".format(self.x) f1 = Foo(10) f2 = Foo(20) print("f1 + f2 = {}".format(f1 + f2)) print("f1 + 10 = {}".format(f1 + 50))
  • 15. Reversible? • What if we now say print("10 + f1 = {}".format(50 + f1)) • What will Python do?
  • 16. f1 + 10 = Instance of f, x = 60 Traceback (most recent call last): File "./foo.py", line 29, in <module> print("10 + f1 = {}".format(50 + f1)) TypeError: unsupported operand type(s) for +: 'int' and 'Foo'
  • 17. __radd__ • Auto-reversing: We get self and other, and now invoke our previously defined __add__: def __radd__(self, other): return self.__add__(other)
  • 18. How does this work? • Python tries to do it the usual way • It gets NotImplemented back • Not an exception! • An instance of Not ImplementedType! • Python then tries (in desperation) to turn things around… and thus, __radd__
  • 19. Type conversions • You probably know about __str__ already • But what about __int__? Or even __hex__?
  • 20. Example def __int__(self): return int(self.x) def __hex__(self): return hex(int(self.x))
  • 21. Boolean conversions • Your object will always be considered True in a boolean context, unless you define __nonzero__ (__bool__ in Python 3)
  • 22. Example class Foo(object): pass f = Foo() >>> bool(f) True
  • 23. But with __nonzero__… class Foo(object): def __init__(self, x): self.x = x def __nonzero__(self): return bool(self.x) >>> f = Foo(1) >>> bool(f) True >>> f = Foo(0) >>> bool(f) False
  • 24. Format • Originally, Python used the % syntax for pseudo- interpolation: name = 'Reuven' print('Hello %s' % name) • But there are lots of problems with it, so it's better to use str.format
  • 26. Pad it! name = 'Reuven' print('Hello, {0:20}!'.format(name))
  • 28. Custom formats • It turns out that our objects can also handle these custom formats! • If we define __format__ on our object, then it'll get the format code (i.e., whatever comes after the :) • We can then decide what to do with it
  • 29. class Person(object): def __init__(self, given, family): self.given = given self.family = family def __format__(self, format): if format == 'familyfirst': return "{} {}".format(self.family, self.given) elif format == 'givenfirst': return "{} {}".format(self.given, self.family) else: return "BAD FORMAT CODE"
  • 30. Using it >>> p = Person('Reuven', 'Lerner') >>> "Hello, {}".format(p) 'Hello, BAD FORMAT CODE' >>> "Hello, {:familyfirst}".format(p) 'Hello, Lerner Reuven' >>> "Hello, {:givenfirst}".format(p) 'Hello, Reuven Lerner'
  • 31. Pickle • Pickle allows you to serialize, or marshall objects • You can then store them to disk, or send them on the network • Pickle works with most built-in Python data types, and classes built on those types
  • 32. Pickling simple data import pickle d = {'a':1, 'b':2} p = pickle.dumps(d) new_d = pickle.loads(p)
  • 33. Custom pickling • Define some magic methods (of course) to customize your pickling: • __getstate__ returns a dictionary that should reflect the object. Want to add to (or remove from) what is being pickled? Just modify a copy of self.__dict__ and return it! • Don't modify the dictionary itself…
  • 34. Example class Foo(object): def __init__(self, x): self.x = x def __getstate__(self): odict = self.__dict__.copy() odict['y'] = self.x * 2 return odict >>> f = Foo(10) >>> p = pickle.dumps(f) >>> new_f = pickle.loads(p) >>> vars(new_f) {'x': 10, 'y': 20}
  • 35. Equality • What makes two object equal? • By default in Python, they're only equal if their ids are equal • (Yes, every object has a unique ID number — use the "id" function to find it!) • You change this by defining __eq__!
  • 36. Changing equality class Foo(object): def __init__(self, x): self.x = x def __eq__(self, other): return self.x == other.x >>> f1 = Foo(10) >>> f2 = Foo(10) >>> f1 == f2 True
  • 37. Hashing • If two objects are equal, then maybe they should hash to the same value, right? • We can set the __hash__ attribute to be a method that returns whatever we want
  • 38. Playing with __hash__ class Foo(object): def __init__(self, x): self.x = x def __hash__(self): return hash(self.x) >>> f = Foo('a') >>> hash(f) 12416037344 >>> hash('a') 12416037344 f = Foo(1) >>> hash(f) 1
  • 39. Messing around with hashing • What if we have __hash__ return a random number each time? • That will have some interesting consequences…
  • 40. Questions? • Follow me: @reuvenmlerner • Buy my book, "Practice Makes Python" • 10% off with offer code "webinar" • Get my newsletter: http://lerner.co.il/newsletter • Read my blog: http://blog.lerner.co.il/ • Learn a bit: http://DailyTechVideo.com/