SlideShare a Scribd company logo
1 of 9
Download to read offline
Python magic methods
by Nacho Gentile
What is a method?
• A method is similar to a function except it’s a member of
an object or class.
• Normally, we use the syntax object.method() to call a
method, for example datetime.now()
• The first parameter of an object method is always “self”
Example of method:
class Runner:	
	 def run(self, meters):	
	 	 pass
What are magic methods
• Special methods that you can define to add
“magic” to your classes
• Magic methods are surrounded by two
underscores, e.g. __init__
Some of the things we can
do with magic methods
• Give instructions to classes about what to do when creating an object
obj1 = MyClass() # __init__	
!
• Explain classes how to arithmetically add together
obj1 + obj2 # __radd__	
!
• Define how the object will look like when printed
print obj1 # __str__	
• Explain classes how to perform boolean operations on them
obj1 > obj2 # __gt__, __lt__, __cmp__
The runners example
• We need to represent runners profile for a runners
website
• Each runner profile is related to a list of race statistics
• Each race statistic tracks distance ran and calories
used during the race
• We want to know: the total statistics for all races
(distance and calories) and to compare runners by
total distances made.
The runners example
class RaceStatistics:	
def __init__(self, distance, calories):	
self.distance = distance	
self.calories = calories	
!
def __radd__(self, other):	
if other.__class__ == self.__class__:	
return RaceStatistics(self.distance + other.distance,	
self.calories + other.calories)	
else:	
return self
class Runner:	
def __init__(self, name):	
self.name = name	
self.races = []	
!
def __str__(self):	
return "Runner %s" % self.name	
!
def add_race(self, distance, calories):	
new_run = RaceStatistics(distance, calories)	
self.races.append(new_run)	
!
def get_all_races_statistics(self):	
return sum(self.races)	
!
def get_total_distance(self):	
return self.get_all_races_statistics().distance	
!
def get_total_calories(self):	
return self.get_all_races_statistics().calories	
!
def __cmp__(self, other):	
return self.get_total_distance() == other.get_total_distance()	
!
def __lt__(self, other):	
return self.get_total_distance() < other.get_total_distance()	
!
def __gt__(self, other):	
return self.get_total_distance() > other.get_total_distance()
nacho = Runner("Nacho")	
nacho.add_race(distance=15, calories=150)	
nacho.add_race(distance=20, calories=450)	
nacho.add_race(distance=14, calories=250)	
!
manuel = Runner("Manuel")	
manuel.add_race(distance=15, calories=150)	
manuel.add_race(distance=20, calories=450)	
manuel.add_race(distance=14, calories=250)	
!
print nacho	
> Runner Nacho	
!
nacho.get_total_distance()	
> 49	
!
nacho.get_total_calories()	
> 850	
!
nacho == manuel	
> True	
!
manuel.add_race(distance=14, calories=250)	
!
if nacho > manuel:	
print "%s is the best runner" % nacho	
elif nacho < manuel:	
print "%s is the best runner" % manuel	
else:	
print "%s and %s are both good" % (nacho, manuel)	
> Runner Manuel is the best runner
Thank you

More Related Content

What's hot

JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashBret Little
 
Ruby Development and MongoMapper (John Nunemaker)
Ruby Development and MongoMapper (John Nunemaker)Ruby Development and MongoMapper (John Nunemaker)
Ruby Development and MongoMapper (John Nunemaker)MongoSF
 
Moose talk at FOSDEM 2011 (Perl devroom)
Moose talk at FOSDEM 2011 (Perl devroom)Moose talk at FOSDEM 2011 (Perl devroom)
Moose talk at FOSDEM 2011 (Perl devroom)xSawyer
 
Moose (Perl 5)
Moose (Perl 5)Moose (Perl 5)
Moose (Perl 5)xSawyer
 
Introduction to Moose
Introduction to MooseIntroduction to Moose
Introduction to Moosethashaa
 
Python 표준 라이브러리
Python 표준 라이브러리Python 표준 라이브러리
Python 표준 라이브러리용 최
 
Scaling modern JVM applications with Akka toolkit
Scaling modern JVM applications with Akka toolkitScaling modern JVM applications with Akka toolkit
Scaling modern JVM applications with Akka toolkitBojan Babic
 
MTDDC 2010.2.5 Tokyo - Brand new API
MTDDC 2010.2.5 Tokyo - Brand new APIMTDDC 2010.2.5 Tokyo - Brand new API
MTDDC 2010.2.5 Tokyo - Brand new APISix Apart KK
 
Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Bozhidar Boshnakov
 
OO Perl with Moose
OO Perl with MooseOO Perl with Moose
OO Perl with MooseNelo Onyiah
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1saydin_soft
 

What's hot (18)

JS OO and Closures
JS OO and ClosuresJS OO and Closures
JS OO and Closures
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
 
Ruby Development and MongoMapper (John Nunemaker)
Ruby Development and MongoMapper (John Nunemaker)Ruby Development and MongoMapper (John Nunemaker)
Ruby Development and MongoMapper (John Nunemaker)
 
What are arrays in java script
What are arrays in java scriptWhat are arrays in java script
What are arrays in java script
 
Moose talk at FOSDEM 2011 (Perl devroom)
Moose talk at FOSDEM 2011 (Perl devroom)Moose talk at FOSDEM 2011 (Perl devroom)
Moose talk at FOSDEM 2011 (Perl devroom)
 
Django Pro ORM
Django Pro ORMDjango Pro ORM
Django Pro ORM
 
Python - Lecture 3
Python - Lecture 3Python - Lecture 3
Python - Lecture 3
 
Codeware
CodewareCodeware
Codeware
 
Moose (Perl 5)
Moose (Perl 5)Moose (Perl 5)
Moose (Perl 5)
 
Introduction to Moose
Introduction to MooseIntroduction to Moose
Introduction to Moose
 
Python 표준 라이브러리
Python 표준 라이브러리Python 표준 라이브러리
Python 표준 라이브러리
 
Scaling modern JVM applications with Akka toolkit
Scaling modern JVM applications with Akka toolkitScaling modern JVM applications with Akka toolkit
Scaling modern JVM applications with Akka toolkit
 
MTDDC 2010.2.5 Tokyo - Brand new API
MTDDC 2010.2.5 Tokyo - Brand new APIMTDDC 2010.2.5 Tokyo - Brand new API
MTDDC 2010.2.5 Tokyo - Brand new API
 
Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)
 
Python Part 2
Python Part 2Python Part 2
Python Part 2
 
OO Perl with Moose
OO Perl with MooseOO Perl with Moose
OO Perl with Moose
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1
 
Python Part 1
Python Part 1Python Part 1
Python Part 1
 

Viewers also liked

An Introduction to Agile - Prashant Pund, AgileSoft.
An Introduction to Agile - Prashant Pund, AgileSoft.An Introduction to Agile - Prashant Pund, AgileSoft.
An Introduction to Agile - Prashant Pund, AgileSoft.Pune OpenCoffee Club
 
Management and organizations
Management and organizationsManagement and organizations
Management and organizationsFanny Sheeran
 
Project Management - Back To Basics
Project Management - Back To BasicsProject Management - Back To Basics
Project Management - Back To BasicsiHub
 
Second Language Teaching Methods
Second Language Teaching MethodsSecond Language Teaching Methods
Second Language Teaching Methodsguest0c02e6
 
Meaning,nature,scope,process of management & approaches of a system
Meaning,nature,scope,process of management & approaches of a systemMeaning,nature,scope,process of management & approaches of a system
Meaning,nature,scope,process of management & approaches of a systemsadhikakatiyar
 
Ch 1 introduction to management and organizations
Ch 1 introduction to management and organizationsCh 1 introduction to management and organizations
Ch 1 introduction to management and organizationsNardin A
 

Viewers also liked (8)

Teaching methods
Teaching methodsTeaching methods
Teaching methods
 
An Introduction to Agile - Prashant Pund, AgileSoft.
An Introduction to Agile - Prashant Pund, AgileSoft.An Introduction to Agile - Prashant Pund, AgileSoft.
An Introduction to Agile - Prashant Pund, AgileSoft.
 
Management and organizations
Management and organizationsManagement and organizations
Management and organizations
 
Project Management - Back To Basics
Project Management - Back To BasicsProject Management - Back To Basics
Project Management - Back To Basics
 
RESEARCH WRITING - Apa References Style
RESEARCH WRITING - Apa References StyleRESEARCH WRITING - Apa References Style
RESEARCH WRITING - Apa References Style
 
Second Language Teaching Methods
Second Language Teaching MethodsSecond Language Teaching Methods
Second Language Teaching Methods
 
Meaning,nature,scope,process of management & approaches of a system
Meaning,nature,scope,process of management & approaches of a systemMeaning,nature,scope,process of management & approaches of a system
Meaning,nature,scope,process of management & approaches of a system
 
Ch 1 introduction to management and organizations
Ch 1 introduction to management and organizationsCh 1 introduction to management and organizations
Ch 1 introduction to management and organizations
 

Similar to Python Magic Methods: a practical example

Data Structures and Algorithms in Python
Data Structures and Algorithms in PythonData Structures and Algorithms in Python
Data Structures and Algorithms in PythonJakeLWright
 
Test Doubles - stubs, spies & mocks
Test Doubles - stubs, spies & mocksTest Doubles - stubs, spies & mocks
Test Doubles - stubs, spies & mocksRubén Bernárdez
 
08-classes-objects.ppt
08-classes-objects.ppt08-classes-objects.ppt
08-classes-objects.pptssuser419267
 
08-classes-objects.ppt
08-classes-objects.ppt08-classes-objects.ppt
08-classes-objects.pptUmooraMinhaji
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfSudhanshiBakre1
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundationKevlin Henney
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfSudhanshiBakre1
 
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.pptmuneshwarbisen1
 
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
 
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 BORSANIYAMaulik Borsaniya
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲Mohammad Reza Kamalifard
 
Python presentation
Python presentationPython presentation
Python presentationJulia437584
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Threeamiable_indian
 
Exception handling and function in python
Exception handling and function in pythonException handling and function in python
Exception handling and function in pythonTMARAGATHAM
 

Similar to Python Magic Methods: a practical example (20)

Data Structures and Algorithms in Python
Data Structures and Algorithms in PythonData Structures and Algorithms in Python
Data Structures and Algorithms in Python
 
Python - OOP Programming
Python - OOP ProgrammingPython - OOP Programming
Python - OOP Programming
 
Test Doubles - stubs, spies & mocks
Test Doubles - stubs, spies & mocksTest Doubles - stubs, spies & mocks
Test Doubles - stubs, spies & mocks
 
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_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundation
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
 
6 Object Oriented Programming
6 Object Oriented Programming6 Object Oriented Programming
6 Object Oriented Programming
 
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
 
Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods
 
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 note.pdf
python note.pdfpython note.pdf
python note.pdf
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
 
Python presentation
Python presentationPython presentation
Python presentation
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
 
Java method
Java methodJava method
Java method
 
Exception handling and function in python
Exception handling and function in pythonException handling and function in python
Exception handling and function in python
 
Introduction to OOP in Python
Introduction to OOP in PythonIntroduction to OOP in Python
Introduction to OOP in Python
 

Recently uploaded

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 

Recently uploaded (20)

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 

Python Magic Methods: a practical example

  • 1. Python magic methods by Nacho Gentile
  • 2. What is a method? • A method is similar to a function except it’s a member of an object or class. • Normally, we use the syntax object.method() to call a method, for example datetime.now() • The first parameter of an object method is always “self” Example of method: class Runner: def run(self, meters): pass
  • 3. What are magic methods • Special methods that you can define to add “magic” to your classes • Magic methods are surrounded by two underscores, e.g. __init__
  • 4. Some of the things we can do with magic methods • Give instructions to classes about what to do when creating an object obj1 = MyClass() # __init__ ! • Explain classes how to arithmetically add together obj1 + obj2 # __radd__ ! • Define how the object will look like when printed print obj1 # __str__ • Explain classes how to perform boolean operations on them obj1 > obj2 # __gt__, __lt__, __cmp__
  • 5. The runners example • We need to represent runners profile for a runners website • Each runner profile is related to a list of race statistics • Each race statistic tracks distance ran and calories used during the race • We want to know: the total statistics for all races (distance and calories) and to compare runners by total distances made.
  • 6. The runners example class RaceStatistics: def __init__(self, distance, calories): self.distance = distance self.calories = calories ! def __radd__(self, other): if other.__class__ == self.__class__: return RaceStatistics(self.distance + other.distance, self.calories + other.calories) else: return self
  • 7. class Runner: def __init__(self, name): self.name = name self.races = [] ! def __str__(self): return "Runner %s" % self.name ! def add_race(self, distance, calories): new_run = RaceStatistics(distance, calories) self.races.append(new_run) ! def get_all_races_statistics(self): return sum(self.races) ! def get_total_distance(self): return self.get_all_races_statistics().distance ! def get_total_calories(self): return self.get_all_races_statistics().calories ! def __cmp__(self, other): return self.get_total_distance() == other.get_total_distance() ! def __lt__(self, other): return self.get_total_distance() < other.get_total_distance() ! def __gt__(self, other): return self.get_total_distance() > other.get_total_distance()
  • 8. nacho = Runner("Nacho") nacho.add_race(distance=15, calories=150) nacho.add_race(distance=20, calories=450) nacho.add_race(distance=14, calories=250) ! manuel = Runner("Manuel") manuel.add_race(distance=15, calories=150) manuel.add_race(distance=20, calories=450) manuel.add_race(distance=14, calories=250) ! print nacho > Runner Nacho ! nacho.get_total_distance() > 49 ! nacho.get_total_calories() > 850 ! nacho == manuel > True ! manuel.add_race(distance=14, calories=250) ! if nacho > manuel: print "%s is the best runner" % nacho elif nacho < manuel: print "%s is the best runner" % manuel else: print "%s and %s are both good" % (nacho, manuel) > Runner Manuel is the best runner