1

I am new to python programming, and I've now reached the section on OOP in the Python book. I am confused about method definitions in python classes.

What is the difference between:

def __add__(self):
  pass

and

def add(self):
  pass

I'll be thankful if you could clarify this for me; thank you guys.

g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
  • Usually an underscore at the beginning means that its meant for use internally for that object and not for public use. EDIT: it was single underscores originally, with double underscores it means you are implementing the behavior of `object + object` –  Mar 05 '14 at 18:05
  • well they are different names (also the one with underscores is a special magic function) – Joran Beasley Mar 05 '14 at 18:07
  • __add__ is used to defined the addition (with a "+") operation, see here: http://effbot.org/pyref/__add__.htm – Svend Mar 05 '14 at 18:08

3 Answers3

1

Methods that begin and end with underscores like __add__(...) can be used to override existing functionality while a method like add(...) without the underscores is a new user-defined method. The difference would be:

With __add__(self) , you could call thisObj + otherObj

With add(self), you would call thisObj.add(otherObj)

So __add__, __sub__, __call__, etc. override existing operators or functionality.

Micah Smith
  • 4,203
  • 22
  • 28
1

Fundamentally, there is no difference. One is a method called __add__ and the other is a method called add.

However, this is a convention which the Python interpreter, and various libraries, use to designate methods that are somehow "special". They are called magic methods. For example, a + b is essentially syntactic sugar for a.__add__(b). Really:

>>> (1).__add__(2)
3

This means if you create a class for which you want addition to be meaningful, instead of calling your method, say, addTo and then doing foo.addTo(bar), you can call the method __add__ and do foo + bar instead.

Other magic methods: a - b is equivalent to a.__sub__(b), len(a) is equivalent to a.__len__(), cmp(a, b) is equivalent to a.__cmp__(b). a = MyClass() causes the new object's __init__ method to be called. And many more.

Claudiu
  • 224,032
  • 165
  • 485
  • 680
0

Methods in Python with double underscores before and after their names are called commonly called magic method, and are used to define certain behaviours for objects.

For example the my_object.__add__() method would be implicitly called when your object was used as part of an addition

>>> my_object + another_object

Here is a good resource of Python’s magic methods, aka “dunder” methods.

dannymilsom
  • 2,386
  • 1
  • 18
  • 19