Python Constructor Method with Examples

Python Constructor

Python Constructor Method

Python uses a special method called a Python Constructor method. Python allows you to define only one per class. Also known as the __init__() method, it will be the first method definition of a class and its syntax is,

def __init__(self, parameter_1, parameter_2, …., parameter_n):

The __init__() method defines and initializes the instance variables. It is invoked as soon as an object of a class is instantiated. The __init__() method for a newly created object is automatically executed with all of its parameters. The __init__() method is indeed a special method as other methods do not receive this treatment. The parameters for __init__() method are initialized with the arguments that you had passed during the instantiation of the class object. Class methods that begin with a double underscore (__) are called special methods as they have special meaning. The number of arguments during the instantiation of the class object should be equivalent to the number of parameters in __init__() method (excluding the self parameter). When you create an object for a class, it is called an instance of a class.

The terms object and instance of a class are the same thing and are often used interchangeably.

Example: Program to Illustrate Multiple Parameters in __init__() Python Constructor Method

When we call the class object, a new instance of the class is created, and the __init__() method for this new object is immediately executed with all the parameters that we passed to the class object. As the __init__() method is automatically initialized, no need to explicitly call it, instead pass the arguments in the parentheses following the class name when you create a new instance of the class. Since self is the instance of a class, self.mobile_name = name is equivalent to saying nokia.mobile_name = name. Methods have access to all the data attributes contained during the instance of an object. Inside the methods, you can access and modify the values of instance variables that you had previously set on self. Because they use self, they require an instance of the class in order to be used. For this reason, they are also referred to as “instance methods”. After an object has been created, you should not use the object name itself to call the __init__() Python Constructor method directly. For example, the expression object_name.__init__() is not recommended. The __init__() method never returns a value.

Example: Write Python Program to Calculate the Arc Length of an Angle by Assigning Values to the Radius and Angle Data Attributes of the class ArcLength

In Python, you can directly access the data attributes using objects. The data attributes radius and angle are added to the __init__() method of the ArcLength class. The arc length of an angle is calculated in calculate_arc_length() method. These data attributes can be referenced outside the class through the al object. When the object al is created, each of the data attributes radius and angle in the __init__() method are initialized to zero and the object al is passed to the self parameter, which essentially becomes al. radius = 0 and al.angle = 0. On execution of the expressions, al.radius = 9 and al.angle = 75, the values of data attributes are changed to the latest value. When the method calculate_arc_length() is referenced through al objects, the latest values are reflected for the data attributes accessed through the self. It is good practice to include import statements before defining class itself.

Classes with Multiple Objects in Python Constructor Method

Multiple objects for a class can be created while attaching a unique copy of data attributes and methods of the class to each of these objects.

Example: Program to Illustrate the Creation of Multiple Objects for a Class

Here, three objects, vulture, crane, and emu, are created for the Birds class. All of these objects belong to the same class, so they have the same data attribute but different values for each of those data attributes. Objects can also have their own methods to operate on their data attributes. A method is always invoked relative to some object of its class. During object instantiation, each object receives a unique copy of data attribute and method is bundled together. This ensures that correct data attributes and methods are used that are specific to a particular object. The self variable is initialized with the particular object of the class that is created during instantiation and the parameters of __init__() Python Constructor is initialized with the arguments passed on to that class object. Now we have three objects whose data attributes have different values. In this case, vulture.flying_birds() will output “Griffon Vulture flies above clouds,” crane.flyingbirds() will output “Common Crane flies above cloud,” and emu.non_flying_birds() will output “Emu is the national bird of Australia”. Notice the use of bird_name in. Even though they have the same name, they are unique. The bird_name in __init__() method definition header is used as a parameter while the bird_name referenced by self within the method is an instance variable.

Using Objects as Arguments in Python Constructor Method

An object can be passed to a calling function as an argument.

Example: Program to Demonstrate the Passing of an Object as an Argument to a Function Call

In the class Track, the __init__() method is added with the song and artist data attributes. The print_track_info() function receives an object as parameter. The object singer  of Track class is passed as an argument to print_track_info() function. (Note: It is a function defined outside the class and not a method.) Since you are passing an object of a class as an argument, you have access to all the data attributes attached to that object.

Objects as Return Values in Python Constructor Method

It is important to note that everything in Python is an object, including classes. Anything that can be used as a value (int, str, float, functions, modules, etc.) is implemented as an object. The id() function is used to find the identity of the location of the object in memory. The syntax for id() function is, id(object). This function returns the “identity” of an object. This is an integer (or long integer), which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. You can check whether an object is an instance of a given class or not by using the isinstance() function. The syntax for isinstance() function is, where the object is an object instance and classinfo can be a class, or a tuple containing classes, or other tuples. The isinstance() function returns a Boolean stating whether the object is an instance or subclass of another object.

Example: Write Python Program to Determine Whether the Point Lies Inside the Circle, On the Circle or Outside the Circle

If you have a circle with the center as (center_x, center_y) and radius as radius, then you can test if a given point with coordinates (x, y) is inside or outside, or on the circle using the formula (x – center_x) ^ 2 + (y – center_y) ^ 2 < radius ^ 2. Please note, the points that satisfy this equation with < operator replaced by == operator are considered to be on the circle and the points that satisfy this equation with < operator replaced by > operator are considered to be outside the circle. The point object is used to invoke check_point_status() method. This check_point_status() method returns the self object itself. The returned_object variable is used to store the returned object. Both point and returned_object are used to store an instance of the same class – and they point to the same location in memory, which is why their values are the same.

Related Article:

Python Pandas DataFrame basics

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button