Python class special methods or magic methods
What happens when we create an object in python class ?
def __init__(self, city, pin):
self.city = city
self.pin = 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)
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
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) )
now use the “+” operator with two vectors
>>> v1 = Vector(1, 2)
>>> v2 = Vector(10, 13)
>>> v3 = v1 + v2
When statement “v3 = v1 + v2 “ executes “__add__” is called and it returns a new Vector object.
for more information please visit the python docs