SlideShare a Scribd company logo
Magic Methods
Python meetup
Ines Jelovac
Zagreb, 21 February 2017
Why magic methods?
What are magic methods?
● Methods with double underscores at the beginning and the
end
○ __init__
○ __str__
● Where is magic?
○ Magic methods are not invoked directly!
How magic methods are invoked?
● Calling Python’s built in functions
len([1, 2, 3])
● Using operators
1 + 1
5 > 3
● Using for loop
for x in [1, 2, 3]:
print(x)
Which methods are invoked?
● Calling Python’s built in functions
len([1, 2, 3]) # __len__()
● Using operators
1 + 1 # __add__()
5 > 3 # __gt__()
● Using for loop
for x in [1, 2, 3]: # __iter__()
print(x) # __next__()
Example: __len__
x = [1, 2, 3, 4, 5]
len(x)
>> 5
Magic method:
x.__len__()
Example: __str__
from datetime import datetime
x = datetime.now()
print(x)
>> 2017-02-21 18:15:02.161633
Magic method:
x.__str__()
Example: __getitem__
x = {
‘A’: 1,
‘B’: 2
}
x[‘A’]
>> 1
Magic method:
x.__getitem__(key) # key=’A’
Example: __setitem__
x = {1: ‘a’, 2: ‘3’}
x[3] = ‘c’ # x.__setitem__(self, name, value)
Another magic method:
3.__hash__()
● Must be implemented if instance is
used in hashable collections
● Returns integer, immutable
for instance
● Works with __cmp__ or __eq__
When to implement?
● to control string representation of an object
○ __repr__
○ __str__
● to initialize an instance
○ __init__
● when writing libraries, frameworks
○ to make objects behave like built-in types
○ Django example:
■ model_instance_a == model_instance_b
Implementing: __init__
● “Constructor”
○ __new__
○ __init__
● Example
class ComplexNumber:
def __init__(self, x, y):
self.x = x # x = Re
self.y = y # y = Im
z = ComplexNumber(3, 5)
Implementing: __str__
● string representation of an object
○ str(x)
○ print(x)
● Example
class ComplexNumber:
...
def __str__(self):
return ‘{} + {}i’.format(self.x, self.y)
Operator overloading: +
complex_number_a = ComplexNumber(3, 5)
complex_number_b = ComplexNumber(2, 1)
complex_number_a + complex_number_b
>> TypeError
● Magic method
○ __add__
○ complex_number_a.__add__(complex_number_b)
Operator overloading: +
● Magic method
○ __add__
● Example
class ComplexNumber:
...
def __add__(self, other):
real = self.x + other.x
imag = self.y + other.y
return ComplexNumber(real, imag)
Operator overloading: +
complex_number_a = ComplexNumber(3, 5)
complex_number_b = ComplexNumber(2, 1)
complex_number_a + complex_number_b
>> 5 + 6i
complex_number_a + 4
>> AttributeError
'int' object has no attribute 'x'
Operator overloading: +
● Magic method
○ __add__
● Example
class ComplexNumber:
…
def __add__(self, other):
if isinstance(other, ComplexNumber):
real = self.x + other.x
imag = self.y + other.y
return ComplexNumber(real, imag)
else:
return ComplexNumber(self.x + other, self.y)
Operator overloading: +
complex_number_a = ComplexNumber(3, 5)
complex_number_a + 4
>> 7 + 5i
4 + complex_number_a
>> TypeError
unsupported operand type(s) for +: 'int' and 'ComplexNumber'
Operator overloading: +
● Magic method
○ __radd__
● Example
class ComplexNumber:
...
def __radd__(self, other):
return self + other
Operator overloading: +
complex_number_a = ComplexNumber(3, 5)
4 + complex_number_a
>> 7 + 5i
complex_number_a += 4
>> 7 + 5i
Implementing: __all__
● example : django/db/__init__.py
__all__ = ['backend', 'connection', 'connections', ...]
● controls * imports
from django.db import *
When not to implement?
class ComplexNumber():
...
def __del__(self):
self.connection.close() # :(
...
del counter # ?
Magic method:
__del__ is called by garbage collector!
Python 2 and Python 3
● String representation
○ Python 2: __str__ and __unicode__
○ Python 3: __str__
● Boolean
○ Python 2: __nonzero__
○ Python 3: __bool__
● Comparison
○ Python 2: __cmp__
○ Python 3: uses other magic methods
Conclusion
● Be aware when magic methods are invoked
○ Some actions invoke more than just one magic method
● Implement them with caution
○ Make sure to understand purpose of
magic method
○ Write documentation

More Related Content

What's hot

Dev Concepts: Data Structures and Algorithms
Dev Concepts: Data Structures and AlgorithmsDev Concepts: Data Structures and Algorithms
Dev Concepts: Data Structures and Algorithms
Svetlin Nakov
 
Los dskn
Los dsknLos dskn
Los dskn
Brenda Jazmin
 
DF1 - Py - Ovcharenko - Theano Tutorial
DF1 - Py - Ovcharenko - Theano TutorialDF1 - Py - Ovcharenko - Theano Tutorial
DF1 - Py - Ovcharenko - Theano Tutorial
MoscowDataFest
 
Coding Test Review1
Coding Test Review1Coding Test Review1
Coding Test Review1
SEMINARGROOT
 
Coding test review 2
Coding test review 2Coding test review 2
Coding test review 2
SEMINARGROOT
 
Arrays, Structures And Enums
Arrays, Structures And EnumsArrays, Structures And Enums
Arrays, Structures And Enums
Bhushan Mulmule
 
Exam matlab1
Exam matlab1Exam matlab1
Exam matlab1
moness
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: Arrays
Svetlin Nakov
 
Comand window1
Comand window1Comand window1
Comand window1
Shobana Sinniah
 
Array matrix example programs - C language
Array matrix example programs - C languageArray matrix example programs - C language
Array matrix example programs - C language
Sk_Group
 
Polynomial Functions
Polynomial FunctionsPolynomial Functions
Polynomial Functions
johns4kr
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
Svetlin Nakov
 
Ode45
Ode45Ode45
Pointers lesson 4 (malloc and its use)
Pointers lesson 4 (malloc and its use)Pointers lesson 4 (malloc and its use)
Pointers lesson 4 (malloc and its use)
SetuMaheshwari1
 
Chapter 7.2
Chapter 7.2Chapter 7.2
Chapter 7.2
sotlsoc
 
Algorithms python arraylistmatrix
Algorithms python arraylistmatrixAlgorithms python arraylistmatrix
Algorithms python arraylistmatrix
Faculty of Science , portsaid Univeristy
 
Quiz 10 cp_sol
Quiz 10 cp_solQuiz 10 cp_sol
Quiz 10 cp_sol
Syeda Seemab Fatima
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
Rakotoarison Louis Frederick
 

What's hot (18)

Dev Concepts: Data Structures and Algorithms
Dev Concepts: Data Structures and AlgorithmsDev Concepts: Data Structures and Algorithms
Dev Concepts: Data Structures and Algorithms
 
Los dskn
Los dsknLos dskn
Los dskn
 
DF1 - Py - Ovcharenko - Theano Tutorial
DF1 - Py - Ovcharenko - Theano TutorialDF1 - Py - Ovcharenko - Theano Tutorial
DF1 - Py - Ovcharenko - Theano Tutorial
 
Coding Test Review1
Coding Test Review1Coding Test Review1
Coding Test Review1
 
Coding test review 2
Coding test review 2Coding test review 2
Coding test review 2
 
Arrays, Structures And Enums
Arrays, Structures And EnumsArrays, Structures And Enums
Arrays, Structures And Enums
 
Exam matlab1
Exam matlab1Exam matlab1
Exam matlab1
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: Arrays
 
Comand window1
Comand window1Comand window1
Comand window1
 
Array matrix example programs - C language
Array matrix example programs - C languageArray matrix example programs - C language
Array matrix example programs - C language
 
Polynomial Functions
Polynomial FunctionsPolynomial Functions
Polynomial Functions
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
 
Ode45
Ode45Ode45
Ode45
 
Pointers lesson 4 (malloc and its use)
Pointers lesson 4 (malloc and its use)Pointers lesson 4 (malloc and its use)
Pointers lesson 4 (malloc and its use)
 
Chapter 7.2
Chapter 7.2Chapter 7.2
Chapter 7.2
 
Algorithms python arraylistmatrix
Algorithms python arraylistmatrixAlgorithms python arraylistmatrix
Algorithms python arraylistmatrix
 
Quiz 10 cp_sol
Quiz 10 cp_solQuiz 10 cp_sol
Quiz 10 cp_sol
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 

Viewers also liked

Django Admin (Python meeutp)
Django Admin (Python meeutp)Django Admin (Python meeutp)
Django Admin (Python meeutp)
Ines Jelovac
 
Getting bigger with flask
Getting bigger with flaskGetting bigger with flask
Getting bigger with flaskJosipKatalinic
 
David Threets Professional Persona Project
David Threets Professional Persona Project David Threets Professional Persona Project
David Threets Professional Persona Project
David Threet
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
Eric Palakovich Carr
 
Starters with Django
Starters with Django Starters with Django
Starters with Django
BeDjango
 
Django로 배우는 쉽고 빠른 웹개발 study 자료
Django로 배우는 쉽고 빠른 웹개발 study 자료Django로 배우는 쉽고 빠른 웹개발 study 자료
Django로 배우는 쉽고 빠른 웹개발 study 자료
Han Sung Kim
 
Open edX vs Moodle
Open edX vs MoodleOpen edX vs Moodle
Open edX vs Moodle
BeDjango
 
Efficient Django
Efficient DjangoEfficient Django
Efficient Django
David Arcos
 
DJango admin interface
DJango admin interfaceDJango admin interface
DJango admin interface
Mahesh Shitole
 
DjangoでさくっとWeb アプリケーション開発をする話
DjangoでさくっとWeb アプリケーション開発をする話DjangoでさくっとWeb アプリケーション開発をする話
DjangoでさくっとWeb アプリケーション開発をする話
Nakazawa Yuichi
 

Viewers also liked (10)

Django Admin (Python meeutp)
Django Admin (Python meeutp)Django Admin (Python meeutp)
Django Admin (Python meeutp)
 
Getting bigger with flask
Getting bigger with flaskGetting bigger with flask
Getting bigger with flask
 
David Threets Professional Persona Project
David Threets Professional Persona Project David Threets Professional Persona Project
David Threets Professional Persona Project
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
 
Starters with Django
Starters with Django Starters with Django
Starters with Django
 
Django로 배우는 쉽고 빠른 웹개발 study 자료
Django로 배우는 쉽고 빠른 웹개발 study 자료Django로 배우는 쉽고 빠른 웹개발 study 자료
Django로 배우는 쉽고 빠른 웹개발 study 자료
 
Open edX vs Moodle
Open edX vs MoodleOpen edX vs Moodle
Open edX vs Moodle
 
Efficient Django
Efficient DjangoEfficient Django
Efficient Django
 
DJango admin interface
DJango admin interfaceDJango admin interface
DJango admin interface
 
DjangoでさくっとWeb アプリケーション開発をする話
DjangoでさくっとWeb アプリケーション開発をする話DjangoでさくっとWeb アプリケーション開発をする話
DjangoでさくっとWeb アプリケーション開発をする話
 

Similar to Magic Methods (Python meetup)

Updated Week 06 and 07 Functions In Python.pptx
Updated Week 06 and 07 Functions In Python.pptxUpdated Week 06 and 07 Functions In Python.pptx
Updated Week 06 and 07 Functions In Python.pptx
momina273888
 
Updated Week 06 and 07 Functions In Python.pptx
Updated Week 06 and 07 Functions In Python.pptxUpdated Week 06 and 07 Functions In Python.pptx
Updated Week 06 and 07 Functions In Python.pptx
CruiseCH
 
Data Structures and Algorithms in Python
Data Structures and Algorithms in PythonData Structures and Algorithms in Python
Data Structures and Algorithms in Python
JakeLWright
 
Introduction of Xgboost
Introduction of XgboostIntroduction of Xgboost
Introduction of Xgboost
michiaki ito
 
Pythonic Math
Pythonic MathPythonic Math
Pythonic Math
Kirby Urner
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Arnaud Joly
 
Operators
OperatorsOperators
Stanford splash spring 2016 basic programming
Stanford splash spring 2016 basic programmingStanford splash spring 2016 basic programming
Stanford splash spring 2016 basic programming
Yu-Sheng (Yosen) Chen
 
C++ MEMORY MANAGEMENT.pptx/ kbibuvvw veovn nveknev ovne onv
C++ MEMORY MANAGEMENT.pptx/ kbibuvvw veovn nveknev ovne onvC++ MEMORY MANAGEMENT.pptx/ kbibuvvw veovn nveknev ovne onv
C++ MEMORY MANAGEMENT.pptx/ kbibuvvw veovn nveknev ovne onv
ChetanRaut43
 
3 analysis.gtm
3 analysis.gtm3 analysis.gtm
3 analysis.gtm
Natarajan Angappan
 
Pytorch for tf_developers
Pytorch for tf_developersPytorch for tf_developers
Pytorch for tf_developers
Abdul Muneer
 
Python - OOP Programming
Python - OOP ProgrammingPython - OOP Programming
Python - OOP Programming
Andrew Ferlitsch
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monads
rkaippully
 
Algorithms with-java-1.0
Algorithms with-java-1.0Algorithms with-java-1.0
Algorithms with-java-1.0
BG Java EE Course
 
Functional python
Functional pythonFunctional python
Functional python
Jesué Junior
 
chapter1.pdf ......................................
chapter1.pdf ......................................chapter1.pdf ......................................
chapter1.pdf ......................................
nourhandardeer3
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2
Mohamed Ahmed
 
Recommender Systems
Recommender SystemsRecommender Systems
Introduction to Artificial Intelligence...pptx
Introduction to Artificial Intelligence...pptxIntroduction to Artificial Intelligence...pptx
Introduction to Artificial Intelligence...pptx
MMCOE, Karvenagar, Pune
 
Refactoring et al
Refactoring et alRefactoring et al
Refactoring et al
Naveenkumar Muguda
 

Similar to Magic Methods (Python meetup) (20)

Updated Week 06 and 07 Functions In Python.pptx
Updated Week 06 and 07 Functions In Python.pptxUpdated Week 06 and 07 Functions In Python.pptx
Updated Week 06 and 07 Functions In Python.pptx
 
Updated Week 06 and 07 Functions In Python.pptx
Updated Week 06 and 07 Functions In Python.pptxUpdated Week 06 and 07 Functions In Python.pptx
Updated Week 06 and 07 Functions In Python.pptx
 
Data Structures and Algorithms in Python
Data Structures and Algorithms in PythonData Structures and Algorithms in Python
Data Structures and Algorithms in Python
 
Introduction of Xgboost
Introduction of XgboostIntroduction of Xgboost
Introduction of Xgboost
 
Pythonic Math
Pythonic MathPythonic Math
Pythonic Math
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
 
Operators
OperatorsOperators
Operators
 
Stanford splash spring 2016 basic programming
Stanford splash spring 2016 basic programmingStanford splash spring 2016 basic programming
Stanford splash spring 2016 basic programming
 
C++ MEMORY MANAGEMENT.pptx/ kbibuvvw veovn nveknev ovne onv
C++ MEMORY MANAGEMENT.pptx/ kbibuvvw veovn nveknev ovne onvC++ MEMORY MANAGEMENT.pptx/ kbibuvvw veovn nveknev ovne onv
C++ MEMORY MANAGEMENT.pptx/ kbibuvvw veovn nveknev ovne onv
 
3 analysis.gtm
3 analysis.gtm3 analysis.gtm
3 analysis.gtm
 
Pytorch for tf_developers
Pytorch for tf_developersPytorch for tf_developers
Pytorch for tf_developers
 
Python - OOP Programming
Python - OOP ProgrammingPython - OOP Programming
Python - OOP Programming
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monads
 
Algorithms with-java-1.0
Algorithms with-java-1.0Algorithms with-java-1.0
Algorithms with-java-1.0
 
Functional python
Functional pythonFunctional python
Functional python
 
chapter1.pdf ......................................
chapter1.pdf ......................................chapter1.pdf ......................................
chapter1.pdf ......................................
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2
 
Recommender Systems
Recommender SystemsRecommender Systems
Recommender Systems
 
Introduction to Artificial Intelligence...pptx
Introduction to Artificial Intelligence...pptxIntroduction to Artificial Intelligence...pptx
Introduction to Artificial Intelligence...pptx
 
Refactoring et al
Refactoring et alRefactoring et al
Refactoring et al
 

Recently uploaded

Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
Intelisync
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
Hiike
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
alexjohnson7307
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
Shinana2
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Precisely
 
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
Data Hops
 

Recently uploaded (20)

Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
 
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
 

Magic Methods (Python meetup)

  • 1. Magic Methods Python meetup Ines Jelovac Zagreb, 21 February 2017
  • 3. What are magic methods? ● Methods with double underscores at the beginning and the end ○ __init__ ○ __str__ ● Where is magic? ○ Magic methods are not invoked directly!
  • 4. How magic methods are invoked? ● Calling Python’s built in functions len([1, 2, 3]) ● Using operators 1 + 1 5 > 3 ● Using for loop for x in [1, 2, 3]: print(x)
  • 5. Which methods are invoked? ● Calling Python’s built in functions len([1, 2, 3]) # __len__() ● Using operators 1 + 1 # __add__() 5 > 3 # __gt__() ● Using for loop for x in [1, 2, 3]: # __iter__() print(x) # __next__()
  • 6. Example: __len__ x = [1, 2, 3, 4, 5] len(x) >> 5 Magic method: x.__len__()
  • 7. Example: __str__ from datetime import datetime x = datetime.now() print(x) >> 2017-02-21 18:15:02.161633 Magic method: x.__str__()
  • 8. Example: __getitem__ x = { ‘A’: 1, ‘B’: 2 } x[‘A’] >> 1 Magic method: x.__getitem__(key) # key=’A’
  • 9. Example: __setitem__ x = {1: ‘a’, 2: ‘3’} x[3] = ‘c’ # x.__setitem__(self, name, value) Another magic method: 3.__hash__() ● Must be implemented if instance is used in hashable collections ● Returns integer, immutable for instance ● Works with __cmp__ or __eq__
  • 10. When to implement? ● to control string representation of an object ○ __repr__ ○ __str__ ● to initialize an instance ○ __init__ ● when writing libraries, frameworks ○ to make objects behave like built-in types ○ Django example: ■ model_instance_a == model_instance_b
  • 11. Implementing: __init__ ● “Constructor” ○ __new__ ○ __init__ ● Example class ComplexNumber: def __init__(self, x, y): self.x = x # x = Re self.y = y # y = Im z = ComplexNumber(3, 5)
  • 12. Implementing: __str__ ● string representation of an object ○ str(x) ○ print(x) ● Example class ComplexNumber: ... def __str__(self): return ‘{} + {}i’.format(self.x, self.y)
  • 13. Operator overloading: + complex_number_a = ComplexNumber(3, 5) complex_number_b = ComplexNumber(2, 1) complex_number_a + complex_number_b >> TypeError ● Magic method ○ __add__ ○ complex_number_a.__add__(complex_number_b)
  • 14. Operator overloading: + ● Magic method ○ __add__ ● Example class ComplexNumber: ... def __add__(self, other): real = self.x + other.x imag = self.y + other.y return ComplexNumber(real, imag)
  • 15. Operator overloading: + complex_number_a = ComplexNumber(3, 5) complex_number_b = ComplexNumber(2, 1) complex_number_a + complex_number_b >> 5 + 6i complex_number_a + 4 >> AttributeError 'int' object has no attribute 'x'
  • 16. Operator overloading: + ● Magic method ○ __add__ ● Example class ComplexNumber: … def __add__(self, other): if isinstance(other, ComplexNumber): real = self.x + other.x imag = self.y + other.y return ComplexNumber(real, imag) else: return ComplexNumber(self.x + other, self.y)
  • 17. Operator overloading: + complex_number_a = ComplexNumber(3, 5) complex_number_a + 4 >> 7 + 5i 4 + complex_number_a >> TypeError unsupported operand type(s) for +: 'int' and 'ComplexNumber'
  • 18. Operator overloading: + ● Magic method ○ __radd__ ● Example class ComplexNumber: ... def __radd__(self, other): return self + other
  • 19. Operator overloading: + complex_number_a = ComplexNumber(3, 5) 4 + complex_number_a >> 7 + 5i complex_number_a += 4 >> 7 + 5i
  • 20. Implementing: __all__ ● example : django/db/__init__.py __all__ = ['backend', 'connection', 'connections', ...] ● controls * imports from django.db import *
  • 21. When not to implement? class ComplexNumber(): ... def __del__(self): self.connection.close() # :( ... del counter # ? Magic method: __del__ is called by garbage collector!
  • 22. Python 2 and Python 3 ● String representation ○ Python 2: __str__ and __unicode__ ○ Python 3: __str__ ● Boolean ○ Python 2: __nonzero__ ○ Python 3: __bool__ ● Comparison ○ Python 2: __cmp__ ○ Python 3: uses other magic methods
  • 23. Conclusion ● Be aware when magic methods are invoked ○ Some actions invoke more than just one magic method ● Implement them with caution ○ Make sure to understand purpose of magic method ○ Write documentation