0% found this document useful (0 votes)
9 views

OBJECT oRIENTED pROGRAMMING pYTHON

Uploaded by

mrimahjembe19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

OBJECT oRIENTED pROGRAMMING pYTHON

Uploaded by

mrimahjembe19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Object Oriented Programming

Constructor
Index
What is a constructor in Python? Explain its purpose and usage.
Differentiate between a parameterless constructor and a parameterized constructor in
Python.
How do you define a constructor in a Python class? Provide an example.
Explain the __init__ method in Python and its role in constructors.
In a class named Person , create a constructor that initializes the name and age
attributes. Provide an example of creating an object of this class.
How can you call a constructor explicitly in Python? Give an example.
What is the significance of the self parameter in Python constructors? Explain with an
example.
Discuss the concept of default constructors in Python. When are they used?
Create a Python class called Rectangle with a constructor that initializes the width
and height attributes. Provide a method to calculate the area of the rectangle.
How can you have multiple constructors in a Python class? Explain with an example.
What is method overloading, and how is it related to constructors in Python?
Explain the use of the super() function in Python constructors. Provide an example.
Create a class called Book with a constructor that initializes the title , author , and
published_year attributes. Provide a method to display book details.
Discuss the differences between constructors and regular methods in Python classes.
Explain the role of the self parameter in instance variable initialization within a
constructor.
How do you prevent a class from having multiple instances by using constructors in
Python? Provide an example.
Create a Python class called Student with a constructor that takes a list of subjects as
a parameter and initializes the subjects attribute.
What is the purpose of the __del__ method in Python classes, and how does it relate
to constructors?
Explain the use of constructor chaining in Python. Provide a practical example.
Create a Python class called Car with a default constructor that initializes the make
and model attributes. Provide a method to display car information.

In [ ]:
Construtor
1. What is a constructor in Python? Explain its purpose and usage.
In Python, a constructor is a special method within a class that is automatically called
when a new instance (object) of the class is created. Constructors are defined using the
init() method.
The purpose of a constructor is to initialize the object's attributes or perform any
necessary setup tasks when an object is created. This can include initializing instance
variables, setting default values, or any other initialization logic required for the object
to be in a valid state.

2. Differentiate between a parameterless constructor and a parameterized


constructor in Python.
Parameterless Constructor:

A parameterless constructor, as the name suggests, does not accept any parameters.It is
defined with the init() method without any additional parameters other than self.It is used
when the initialization logic does not require any external input parameters.It is often used
to set default values or initialize instance variables without relying on external input.

Parameterized Constructor:

A parameterized constructor accepts one or more parameters in addition to the self


parameter.It allows initialization logic to rely on external input provided during object
creation.It is defined with the init() method with parameters other than self.It is used when
the initialization logic requires external data to set up the object.

3. How do you define a constructor in a Python class? Provide an example.


In Python, a constructor is defined using a special method called init(). This method is
automatically called when a new instance (object) of the class is created. Within the init()
method, you can define the initialization logic for the object, such as initializing instance
variables or performing setup tasks.

In [1]: class car:


def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
def display_info(self):
print(f"Car:{self.make}{self.model}{self.year}")
my_car = car("Audi ","R8V10 ",2018)
my_car.display_info()
Car:Audi R8V10 2018

4. Explain the __init__ method in Python and its role in constructors.

In Python, the init() method is a special method that serves as the constructor for a
class. It is automatically called when a new instance (object) of the class is created. The
init() method is where you define the initialization logic for the object, such as
initializing instance variables or performing any necessary setup tasks.

Parameters: The init() method can accept parameters just like any other method in
Python. Typically, the first parameter of init() is self, which refers to the instance being
created. You can also specify additional parameters to initialize the object with external
data

Instance Variables Initialization: Inside the init() method, you initialize instance variables by
assigning values to self.attribute_name. These instance variables can then be accessed and
modified throughout the class methods using self.

5. In a class named Person , create a constructor that initializes the name


and age attributes. Provide an example of creating an object of this class

In [2]: class Person:


def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person('Alice', 30)
print(f"Person's Detail: {person1.name},{person1.age}")

Person's Detail: Alice,30

6. How can you call a constructor explicitly in Python? Give an example.

In [3]: class Person:


def __init__(self, name, age):
self.name = name
self.age = age

# Explicitly calling the constructor of the Person class


person2 = Person.__init__(Person, 'Bob', 25)

# Printing out the attributes of the object created by the constructor


print(f"Name: {person2.name}, Age: {person2.age}")

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[3], line 10
7 person2 = Person.__init__(Person, 'Bob', 25)
9 # Printing out the attributes of the object created by the constructor
---> 10 print(f"Name: {person2.name}, Age: {person2.age}")

AttributeError: 'NoneType' object has no attribute 'name'


In Python, you can call a constructor explicitly by using the class name followed by
parentheses, passing the required arguments to the constructor. This is similar to calling any
other method, but you use the class name instead of an instance.This explicit call to the
constructor returns None, as constructors typically don't return anything explicitly. They
initialize the object instead.Then, we try to access the name and age attributes of the object
person2. However, since person2 is None, this results in an error.

7. What is the significance of the self parameter in Python constructors?


Explain with an example.
In Python, the self parameter in constructors (and in all instance methods) refers to the
instance of the class itself. When you call a method on an instance, Python automatically
passes the instance as the first argument to the method. This allows the method to access
and modify attributes of that specific instance.

In [4]: #Here's an example to illustrate the significance of the self parameter in Python c
class person:
def __init__(self,name,age):
self.name=name
self.age=age
def display_details(self):
print(f"Name:{self.name}, Age:{self.name}")
person1=person("ajay",30)
person2=person("vijay",28)
person1.display_details()
person2.display_details()

Name:ajay, Age:ajay
Name:vijay, Age:vijay

Inside the display_details method, self.name and self.age allow access to the name and age
attributes specific to each instance, enabling us to print out the details of each person object
individually.So, self is crucial in Python constructors (and instance methods in general)
because it allows access to the attributes and methods of the specific instance on which the
method is being called.

8. Discuss the concept of default constructors in Python. When are they


used?
In Python, if you don't define an init constructor in your class, Python will provide a
default constructor.The default constructor provided by Python does nothing more than
creating an instance of the class. It doesn't initialize any attributes unless they are
defined as class variables. If your class doesn't have any attributes to initialize or any
other initialization logic to perform, you can omit the init constructor, and Python will
provide a default one for you.
Default constructors can be used when your class doesn't require any initialization logic
or when all attributes have default values, and you don't need to explicitly initialize them
in the constructor. They provide a simple way to create instances of classes without
needing to define constructors explicitly for every class.

9. Create a Python class called Rectangle with a constructor that


initializes the width and height attributes. Provide a method to
calculate the area of the rectangle

In [5]: class Ractangle:


def __init__(self,height,width):
self.height=height
self.width=width
def area(self):
return self.height*self.width
Ract_ABCD=Ractangle(30,40)
print("Area of ractangle:",Ract_ABCD.area())

Area of ractangle: 1200

10. How can you have multiple constructors in a Python class? Explain with
an example.
In Python, while it doesn't natively support method overloading, we can indeed simulate
multiple constructors through various means. One common approach is to use default
arguments along with None checks in the init method.

In [6]: # Here's how you can achieve it:


class Rectangle:
def __init__(self, *args):
if len(args) == 1:
self.width = args[0]
self.height = args[0]
elif len(args) == 2:
self.width = args[0]
self.height = args[1]
else:
raise ValueError("Invalid number of arguments")
def calculate_area(self):
return self.width * self.height

rect1 = Rectangle(5, 10)


print("Area of rect1:", rect1.calculate_area())
square = Rectangle(5)
print("Area of square:", square.calculate_area())

Area of rect1: 50
Area of square: 25

11. What is method overloading, and how is it related to constructors in


Python?
Method overloading is a concept in object-oriented programming where multiple methods
can have the same name but with different parameters or different implementations. This
allows for the same method name to be used for different operations or behaviors based on
the parameters passed to it.Constructors in Python are special methods used for initializing
objects. In Python, the constructor method is named init. Just like other methods, init can be
overloaded by defining multiple methods with the same name but different parameter lists.

In [7]: #Here's an example to illustrate method overloading in Python with constructors:


class overloading:
def __init__(self,a=None,b=None):
if a is not None and b is not None:
self.a=a
self.b=b
elif a is not None:
self.a=a
self.b=0
else:
self.a=0
self.b=0
def display(self):
print(f"a={self.a}, b={self.b}")
obj1=overloading()
obj2=overloading(10)
obj3=overloading(15,25)
obj1.display()
obj2.display()
obj3.display()

a=0, b=0
a=10, b=0
a=15, b=25

12. Explain the use of the super() function in Python constructors.


Provide an example.
The super() function in Python is used to call the constructor or methods of the parent class
from the child class. This is particularly useful when you're working with inheritance and want
to invoke the parent class's constructor to initialize inherited attributes. When you use
super() in a constructor, it allows you to access and invoke the parent class's constructor,
passing along any necessary arguments.

In [9]: class Parent:


def __init__(self,name):
self.name=name
def display(self):
print("Name",self.name)
class child(Parent):
def __init__(self,name,age):
super().__init__(name) #Calling parents class constructer
self.age=age
def display(self):
super().display()
print("Age",self.age)
child_obj = child("Vishal",24)
child_obj.display()

Name Vishal
Age 24

In this example, the Child class inherits from the Parent class. Inside the Child class
constructor, super().init(name) is used to call the constructor of the parent class with the
provided name argument. This ensures that the name attribute of the parent class is
initialized properly. Similarly, within the display method of the Child class, super().display() is
used to invoke the display method of the parent class before displaying the age attribute
specific to the child class.

13.Create a class called Book with a constructor that initializes the title ,
author , and published_year attributes.Provide a method to display
book details

In [11]: class book:


def __init__(self,title,author,published_year):
self.title=title
self.author=author
self.published_year=published_year
def display_details(self):
print("Book Title is",self.title,"The Author is",self.author,"& Published Y
vishal=book("Pride & prejudice","Jane Austen",1813)
vishal.display_details()

Book Title is Pride & prejudice The Author is Jane Austen & Published Year 1813

14. Discuss the differences between constructors and regular methods in


Python classes.
Constructors and regular methods in Python classes serve different purposes and have
distinct characteristics:

1. Purpose :

Constructors: Constructors are special methods used for initializing objects when they are
created. They are called automatically when an object is instantiated from a class.Regular
methods: Regular methods are used to define the behavior of objects. They can perform
various operations on object attributes and can be called explicitly by objects 2. Name
Constructors: Constructors in Python are named init. They always have this special name.
Regular methods: Regular methods can have any valid method name, except for special
methods like init, which are reserved for constructors or other special purposes. 3.
Invocation : Constructors: Constructors are automatically invoked when an object of the
class is created using the class name followed by parentheses. Regular methods: Regular
methods need to be called explicitly using object dot notation, specifying the method name
followed by parentheses.
15. Explain the role of the self parameter in instance variable
initialization within a constructor.
In Python, the self parameter in a class constructor plays a crucial role in instance variable
initialization. When defining a class in Python, methods within that class must include self as
the first parameter. This parameter refers to the instance of the class itsel.When you create
an instance of a class (i.e., an object), Python automatically passes this instance as the first
argument to the constructor and other methods defined within the class. By convention, this
parameter is named self, but we can name it differently if we want.Within the constructor
(init method), self is used to refer to the instance being created. By using self, you can access
and initialize instance variables specific to that particular instance of the class. Instance
variables are unique to each instance of the class, allowing each object to have its own statef

In [13]: #Example
class MyClass:
def __init__(self, x, y):
self.x = x # Initialize instance variable 'x' for this instance
self.y = y # Initialize instance variable 'y' for this instance
obj1 = MyClass(5, 10)
obj2 = MyClass(15, 20)
print("Object 1: x =", obj1.x, ", y =", obj1.y)
print("Object 2: x =", obj2.x, ", y =", obj2.y)

Object 1: x = 5 , y = 10
Object 2: x = 15 , y = 20

16. How do you prevent a class from having multiple instances by using
constructors in Python? Provide an example.
To prevent a class from having multiple instances, you can implement the Singleton design
pattern in Python. The Singleton pattern ensures that only one instance of a class is created
throughout the program's execution. This is achieved by controlling the instantiation process
within the class itself, typically by providing a static method or class method to access the
single instance.

In [14]: #Example:

class Singleton:
_instance=None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance=super().__new__(cls)
return cls._instance
def __init__(self,data):
self.data=data
#creating instances
singleton1 = Singleton(10)
singleton2 = Singleton(20)
print("Data attribute of Singletone 1:", singleton1.data)
print("Data attribute of Singletone 2", singleton2.data)
Data attribute of Singletone 1: 20
Data attribute of Singletone 2 20

17.Create a Python class called Student with a constructor that takes a list
of subjects as a parameter and initializes the subjects attribute

In [15]: class Student:


def __init__(self,subjects):
self.subjcts=subjects
vishal = Student(["maths","chemistry","pysics","statistics","python"])
print("My Subjects are",vishal.subjcts)

My Subjects are ['maths', 'chemistry', 'pysics', 'statistics', 'python']

18. What is the purpose of the __del__ method in Python classes, and
how does it relate to constructors?
The del method in Python classes is a special method used to define the destructor for
an object. It is called when an object is about to be destroyed, i.e., when it's no longer
referenced or needed, and is being garbage collected.The purpose of the del method is
to perform any necessary cleanup or finalization actions before the object is destroyed.
This could involve releasing resources, closing files, or any other cleanup tasks needed
by the object.
The del method is related to constructors (init method) in that they are both special
methods used in object lifecycle management. While the constructor is used for
initializing object state when the object is created, the destructor is used for cleaning up
resources and performing finalization tasks before the object is destroyed. Together,
they help manage the lifecycle of objects in Python classes.

19. Explain the use of constructor chaining in Python. Provide a practical


example.
Constructor chaining, also known as constructor delegation, is a concept in object-oriented
programming where one constructor calls another constructor in the same class or in a
superclass. This allows for code reuse and helps in initializing objects efficiently by reducing
redundancy.In Python, constructor chaining is achieved by using the super() function to call
the constructor of the superclass or the parent class.Constructor chaining allows for cleaner
and more maintainable code by avoiding duplication of initialization logic. It ensures that all
necessary initialization steps are performed properly, whether in the superclass or the
subclass, without having to repeat the code.

In [16]: #Example
class parent:
def __init__(self,name):
self.name=name
print("Parent constructor called")
class child(parent):
def __init__(self,name,age):
super().__init__(name)
self.age=age
print("Child constructor called")
Child = child("Vishal",24)
print("Name & Age:",Child.age,Child.name)

Parent constructor called


Child constructor called
Name & Age: 24 Vishal

20.Create a Python class called Car with a default constructor that


initializes the make and model attributes. Provide a method to display car
information

In [17]: class Car:


def __init__(self, make="Audi", model="R8V10"):
self.make = make
self.model = model

def display_info(self):
print("Car Make:", self.make)
print("Car Model:", self.model)
my_car = Car()
my_car.display_info()

Car Make: Audi


Car Model: R8V10

You might also like