Skip to content

Marina Mele's site

Reflections on family, values, and personal growth

Menu
  • Home
  • About
Menu

Modifying the __add__ method of a Python Class

Posted on April 16, 2014September 26, 2014 by Marina Mele

Learn how you should modify the __add__ method of a Python class to be able to add two instances of a custom object. We also talk about the __radd__ method, necessary to sum a list of instances.

When we sum two objects in Python, likeadd_custom

a + b

what really happens is that the __add__ method of the a object is called:

a.__add__(b)

Which means that we can control the result of a sum of two objects by modifying or defying the __add__ method.

For example, imagine that we define a Day class, which contains the visits and contacts that a web page generates during a day:

class Day(object):
    def __init__(self, visits, contacts):
        self.visits = visits
        self.contacts = contacts
    def __str__(self):
        return “Visits: %i, Contacts: %i” % (self.visits, self.contacts)

and we create two instances of this object:

day1 = Day(10, 1)
day2 = Day(20, 2)

so that

>>> print day1
Visits: 10, Contacts: 1
>>> print day2
Visits: 20, Contacts: 2

We can define the __add__ method to return a Day instance with the total number of visits and contacts:

class Day(object):
    …
    def __add__(self, other):
        total_visits = self.visits + other.visits
        total_contacts = self.contacts + other.contacts
        return Day(total_visits, total_contacts)
    …

and now we can just sum the two instances day1 and day2:

>>> day3 = day1 + day2
>>> print day3
Visits: 30, Contacts: 3

However, if we try:

day4 = sum([day1, day2, day3])

you’ll get an error like

TypeError: unsupported operand type(s) for +: ‘int’ and ‘Day’

This is because the sum method starts with the integer 0, and it tries:

0.__add__(day1)

However, the __add__ method of an integer doesn’t know anything about how to sum a Day instance. Therefore, it tries to call the reverse add method:

day1.__radd__(0)

which is not yet defined! So let’s do that! 😉

class Day(object):
    …
    def __radd__(self, other):
        if other == 0:
            return self
        else:
            return self.__add__(other)
    …

so now, we can use sum to add Day instances!

The full code is:


File: marinamele_add_method.py
------------------------------

class Day(object):
    def __init__(self, visits, contacts):
        self.visits = visits
        self.contacts = contacts

    def __add__(self, other):
        total_visits = self.visits + other.visits
        total_contacts = self.contacts + other.contacts
        return Day(total_visits, total_contacts)

    def __radd__(self, other):
        if other == 0:
            return self
        else:
            return self.__add__(other)

    def __str__(self):
        return "Visits: %i, Contacts: %i" % (self.visits, self.contacts)

day1 = Day(10, 1)
day2 = Day(20, 2)
print day1
# Visits: 10, Contacts: 1
print day2
# Visits: 20, Contacts: 2

day3 = day1 + day2
print day3
# Visits: 30, Contacts: 3

day4 = sum([day1, day2, day3])
print day4
# Visits: 60, Contacts: 6


Django Tip: You can also define the __add__ method in your Django models!

Hope it’s useful!

New Post! Modify the __add__ method of a Python Class to control the sum of two custom objects http://t.co/3IZIn9wG2z
— Marina Mele (@Marina_Mele) April 16, 2014

Marina Melé
Marina Mele

Marina Mele has experience in artificial intelligence implementation and has led tech teams for over a decade. On her personal blog (marinamele.com), she writes about personal growth, family values, AI, and other topics she’s passionate about. Marina also publishes a weekly AI newsletter featuring the latest advancements and innovations in the field (marinamele.substack.com)

Leave a Reply Cancel reply

You must be logged in to post a comment.

Categories

  • Personal Growth and Development
  • Artificial Intelligence
  • Mindful Parenting and Family Life
  • Productivity and Time Management
  • Mindfulness and Wellness
  • Values and Life Lessons
  • Posts en català
  • Other things to learn

Recent Posts

  • BlueSky Social – A Sneak Peek at the Future of Social Media
  • The Incredible Journey of AI Image Generation
  • AI and Fundamental Rights: How the AI Act Aims to Protect Individuals
  • Overcoming Regrets: Finding the Strength to Move Forward
  • Thinking Outside the Box: Creative Problem-Solving with Critical Thinking

RSS

  • Entries RSS
Follow @marina_mele
  • Cookie Policy
  • Privacy Policy
©2023 Marina Mele's site | Built using WordPress and Responsive Blogily theme by Superb
This website uses cookies to improve your experience. If you keep navigating through this website, we'll assume you're ok with this, but you can opt-out if you wish.Accept Read More
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT