In Python, when we define a class and incorporate "magic" features, we introduce special functions known as "magic methods." A prime example of these magic methods includes init and str, which are consistently enclosed by double underscores on either side. By providing access to Python's inherent syntactic capabilities, magic methods can enhance the organization of our classes.
It is possible to combine Python's native classes with our own custom classes. A class that derives from a built-in class is referred to as a child class. This child class inherits all the attributes and methods of its parent class. By leveraging the fundamental built-in functionalities, we can tailor certain operations of our class through the use of magic methods.
__init__ Method
Once we have created an instance of the class, the init method is invoked prior to returning that instance to the class caller. The moment we instantiate the class, this method is triggered automatically, similar to constructors found in well-known programming languages such as C++, Java, C#, PHP, and others. These methods are executed following the new operation, which is why they are termed as initialising methods. It is essential to specify the instance parameters within this method.
Python __init__ Method Example
Let us consider an example to illustrate the init function in Python.
# Python program to show how __init__ method works
# Creating a class
class methods():
def __init__(self, *args):
print ("Now called __init__ magic method, after tha initialised parameters")
self.name = args[0]
self.std = args[1]
self.marks = args[2]
Student = methods("Itika", 11, 98)
print(Student)
print(f"Name, standard, and marks of the student is: \n", Student.name, "\n", Student.std, "\n", Student.marks)
Output:
Now called __init__ magic method, after tha initialised parameters
<__main__.methods object at 0x3701290>
Name, standard, and marks of the student is:
Itika
11
98
__new__ Method
The special method new is automatically invoked by the init method. The instance that is produced by the new method undergoes initialization. To alter the way objects are generated in a custom class, it is necessary to present a customized version of the new magic method. For this static function, we must pass the first argument as a reference to the class for which an object is to be instantiated.
Python __new__ Method Example
Let's consider an illustration to showcase the functionality of the new method in Python.
# Python program to show how __new__ method works
# Creating a class
class Method(object):
def __new__( cls ):
print( "Creating an instance by __new__ method")
return super(Method, cls).__new__(cls)
# Calling the init method
def __init__( self ):
print( "Init method is called here" )
Method()
Output:
Creating an instance by __new__ method
Init method is called here
<__main__.Method at 0x30dfb88>
__add__ Method
The special method add is employed to combine the attributes of class instances. Take, for example, a situation where object1 is an instance of the Method class and object2 is an instance of the Method 1 class. Both of these instances feature an identical attribute named "attribute," which retains any value that is provided upon the instantiation of the class. When tasked with summing the attributes, the add method automatically performs the addition of the corresponding attributes of the instances, specifically executing object1.attribute + object2.attribute when the expression object1 + object2 is evaluated.
Python Example to add two instances without using __add__ magic method
The following code illustrates the process of adding two attributes from instances belonging to different classes without utilizing the add magic method.
# Python program to show how to add two attributes
# Creating a class
class Method:
def __init__(self, argument):
self.attribute = argument
# Creating a second class
class Method_2:
def __init__(self, argument):
self.attribute = argument
# creating the instances
instance_1 = Method(" Attribute")
print(instance_1.attribute)
instance_2 = Method_2(" 27")
print(instance_2.attribute)
# Adding two attributes of the instances
print(instance_2.attribute + instance_1.attribute)
Output:
Attribute
27
27 Attribute
By using __add__ magic method the code changes to this.
Python __add__ Method Example
Let’s consider an example to illustrate the functionality of the add method in Python.
# Python program to show how __add__ method works
# Creating a class
class Method:
def __init__(self, argument):
self.attribute = argument
def __add__(self, object1):
return self.attribute + object1.attribute
# Creating a second class
class Method_2:
def __init__(self, argument):
self.attribute = argument
def __add__(self, object1):
return self.attribute + object1.attribute
instance_1 = Method(" Attribute")
print(instance_1)
instance_2 = Method_2(" 27")
print(instance_2)
print(instance_2 + instance_1)
Output:
<__main__.Method object at 0x37470f0>
<__main__.Method_2 object at 0x376beb8>
27 Attribute
Explanation:
In the script provided, the classes, Method, and Method1 each include a property named "attribute" that holds a string value. We instantiate two objects, instance1 and instance2, assigning them attributes of " Attribute" and " 27" respectively. The add method is utilized to convert the operation instance1 + instance2 into instance1 + instance_2.attribute, resulting in the output ( 27 Attribute).
__repr__ Method
The instance of a class is depicted as a string through the use of the special method repr. This repr method generates a string representation, and it is invoked automatically each time we try to print an object belonging to that class.
Python __repr__ Method Example
Let's consider an example to illustrate the functionality of the repr method in Python.
# Python program to show how __repr__ magic method works
# Creating a class
class Method:
# Calling __init__ method and initializing the attributes of the class
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
# Calling the __repr__ method and providing the string to be printed each time instance is printe
def __repr__(self):
return f"Following are the values of the attributes of the class Method:\nx = {self.x}\ny = {self.y}\nz = {self.z}"
instance = Method(4, 6, 2)
print(instance)
Output:
Following are the values of the attributes of the class Method:
x = 4
y = 6
z = 2
__contains__ Method
In Python, the 'in' membership operator implicitly invokes the contains method. This method can be utilized to check whether a specific element exists within the attributes of an object. It is particularly applicable for attributes that are container types, such as lists, tuples, and similar structures.
Python __contains__ Method Example
To illustrate the function of the contains method in Python, let’s consider a specific example.
# Python code to show how the __contains__ magic method works
# Creating a class
class Method:
# Calling the __init__ method and initializing the attributes
def __init__(self, attribute):
self.attribute = attribute
# Calling the __contains__ method
def __contains__(self, attribute):
return attribute in self.attribute
# Creating an instance of the class
instance = Method([4, 6, 8, 9, 1, 6])
# Checking if a value is present in the container attribute
print("4 is contained in ""attribute"": ", 4 in instance)
print("5 is contained in ""attribute"": ", 5 in instance)
Output:
4 is contained in attribute: True
5 is contained in attribute: False
Explanation:
In the program mentioned earlier, we utilized the contains magic method to check whether a specific integer exists within the "attribute" property. Here, "attribute" refers to a collection of integers. The integer 4 can be found within the provided list of integers that was assigned to the class Method as an attribute. Conversely, the integer 5 does not exist in that list.
__call__ Method
When an instance of a class is invoked, the Python interpreter executes the special method call. This call method allows us to perform an operation directly using the instance's name, eliminating the need to define a separate method for executing particular tasks.
Python __call__ Method Example
Allow us to illustrate the functionality of the call method in Python through an example.
# Python program to show how the __call__ magic method works
# Creating a class
class Method:
# Calling the __init__ method and initializing the attributes
def __init__(self, a):
self.a = a
# Calling the __call__ method to multiply a number to the attribute value
def __call__(self, number):
return self.a * number
# Creating an instance and proving the value to the attribute a
instance = Method(7)
print(instance.a) # Printing the value of the attribute a
# Calling the instance while passing a value which will call the __call__ method
print(instance(5))
Output:
__iter__ Method
In this scenario, a generator object is provided through the iter method. To take advantage of the iter method, we can utilize the iter and next functions.
Python __iter__ Method Example
To illustrate the functionality of the iter method in Python, let us consider a practical example.
# Python program to show how the __iter__ method works
# Creating a class
class Method:
def __init__(self, start_value, stop_value):
self.start = start_value
self.stop = stop_value
def __iter__(self):
for num in range(self.start, self.stop + 1):
yield num ** 2
# Creating an instance
instance = iter(Method(3, 8))
print( next(instance) )
print( next(instance) )
print( next(instance) )
print( next(instance) )
print( next(instance) )
print( next(instance) )
Output:
9
16
25
36
49
64
Explanation:
In the provided code, we have computed the squares of the numbers. The program calculates these squares for the numbers within the defined range (start and stop). The iter method, responsible for generating the squares of the numbers within the specified range, is invoked when we execute the function iter(Method(3, 8)). In this particular instance, with a range from 3 to 8, invoking the next method will yield the outcomes 9, 16, 25, 36, 49, and 64.