Python Programming

Python Constructor Method with Examples

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 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 instance of a class.

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


Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

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

class Mobile:
def __init__(self, name):
self.mobile_name = name
def receive_message(self):
print(f"Receive message using {self.mobile_name} Mobile")
def send_message(self):
print(f"Send message using {self.mobile_name} Mobile")
def main():
nokia = Mobile("Nokia")
nokia.receive_message()
nokia.send_message()
if __name__ == "__main__":
main()
Output
Receive message using Nokia Mobile
Send message using Nokia Mobile

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

import math
class ArcLength:
def __init__(self):
self.radius = 0
self.angle = 0
def calculate_arc_length(self):
result = 2 * math.pi * self.radius * self.angle / 360
print(f"Length of an Arc is {result}")
al = ArcLength()
al.radius = 9
al.angle = 75
print(f"Angle is {al.angle}")
print(f"Radius is {al.radius}")
al.calculate_arc_length()
Output
Angle is 75
Radius is 9
Length of an Arc is 11.780972450961725

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 object, the latest values are reflected for the data attributes accessed through 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

class Birds:
def __init__(self, bird_name):
self.bird_name = bird_name
def flying_birds(self):
print(f"{self.bird_name} flies above clouds")
def non_flying_birds(self):
print(f"{self.bird_name} is the national bird of Australia")
def main():
vulture = Birds("Griffon Vulture")
crane = Birds("Common Crane")
emu = Birds("Emu")
vulture.flying_birds()
crane.flying_birds()
emu.non_flying_birds()
if __name__ == "__main__":
main()
Output
Griffon Vulture flies above clouds
Common Crane flies above clouds
Emu is the national bird of Australia

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 Passing of an Object as an Argument to a Function Call

class Track:
def __init__(self, song, artist):
self.song = song
self.artist = artist
def print_track_info(vocalist):
print(f"Song is '{vocalist.song}'")
print(f"Artist is '{vocalist.artist}'")
singer = Track("The First Time Ever I Saw Your Face", "Roberta Flack")
print_track_info(singer)
Output
Song is "The First Time Ever I Saw Your Face"
Artist is "Roberta Flack"

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

class Circle:
def __init__(self, radius=0, circle_x=0, circle_y=0, point_x=0, point_y=0):
self.radius = radius
self.circle_x_coord = circle_x
self.circle_y_coord = circle_y
self.point_x_coord = point_x
self.point_y_coord = point_y
self.status = ""
def check_point_status(self):
if (self.point_x_coord - self.circle_x_coord) ** 2 + (self.point_y_coord - self.
circle_y_coord) ** 2 < self.radius ** 2:
self.status = f"Point with coordinates {(self.point_x_coord, self.point_y_
coord)} is inside the Circle"
elif (self.point_x_coord - self.circle_x_coord) ** 2 + (self.point_y_coord - self.
circle_y_coord) ** 2 > self.radius ** 2:
self.status = f"Point with coordinates {(self.point_x_coord, self.point_y_
coord)} is outside the Circle"
else:
self.status = f"Point with coordinates {(self.point_x_coord, self.point_y_
coord)} is on the Circle"
return self
def main():
point = Circle(10, 2, 3, 9, 9)
returned_object = point.check_point_status()
print(returned_object.status)
print(f"Is point an instance of Circle Class? {isinstance(point, Circle)}")
print(f"Is returned_object an instance of Circle Class? {isinstance(returned_
object, Circle)}")
print(f"Identity of the location of a point object is {id(point)}")
print(f"Identity of the location of the returned_object object is {id(returned_object)}")
if __name__ == "__main__":
main()
Output
Point with coordinates (9, 9) is inside the Circle
Is point an instance of Circle Class? True
Is returned_object an instance of Circle Class? True
Identity of the location of a point object is 2351304741216
Identity of the location of the returned_object object is 2351304741216

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 same.

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

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

Back to top button