Python class special methods or magic methods

What happens when we create an object in python class ?

class Address(object):
def __init__(self, city, pin): = city = pin

creating instance of the object

a = Address("hyderabad", "500082")

before creating the instance of the class “__new__” method will be called. This method takes parameter “class”, “args”, “kwargs” and It will bind the data type to given class. After it will call the “__init__” method with arguments and keyword arguments.

>>> a = Address.__new__(Address)
>>> type(a)
AttributeError: 'Address' object has no attribute 'city'
# object created but not initialised that's the reason we get error
>>> a.__init__("hyderabad", "500082")
# now we can access the attributes

we can cosider bilt-in methods of an object as magic methods. We can also override the built-in methods functionality.

list of magic methods:

Let’s take an example to override the functionality “+” [__add__] operator

class Vector(object):
def __init__(self, *args):
""" Create a vector, example: v = Vector(1,2) """
if len(args) == 0:
self.values = (0,0)
self.values = args
    def __add__(self, other):
""" Returns the vector addition of self and other """
added = tuple(a + b for a, b in zip(self.values, other.values) )
return Vector(*added)

now use the “+” operator with two vectors

>>> v1 = Vector(1, 2)
>>> v2 = Vector(10, 13)
>>> v3 = v1 + v2
>>> v3.values
(11, 15)

When statement “v3 = v1 + v2 “ executes “__add__” is called and it returns a new Vector object.

for more information please visit the python docs

The article was originally published at MicroPyramid blog

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.