What is Constructor and Destructor in Python oops?
Constructor in Python oops with syntax and example:
Constructor is a special method in the class that is created by using __init__.
The main functionality of constructor is this is called automatically when we create an instance (object) of a class.
It’s primarily used to initialize attributes of the class.
Syntax:
class ClassName:
def __init__(self, parameters):
# Initialize attributes here
What are attributes in Python OOP?
Attributes are variables that are initialized within the constructor (__init__) of a class.
The primary purpose of attributes is to store data specific to an object, allowing you to use these values across different methods within the class.
Syntax:
class class_Name:
def __init__(self, x, y):
self.Variable_1 = x
self.Variable_2 = y
Example of attributes in Python oops:
class attributesExample:
def __init__(self, abc, xyz):
self.name = abc
self.age = xyz
def useris(self):
print("Username is ", self.name, "and age is ", self.age)
obj = attributesExample("kriss moris", 20)
obj.useris()
print(obj.name)
print(obj.age)
Output:
Username is kriss moris and age is 20
kriss moris
20
Example of Constructor in Python oops:
class MyCalculator:
def __init__(self, x, y):
self.val1 = x
self.val2 = y
def sumthis(self):
print("the sum is : ", self.val1 + self.val2)
def subtraction(self):
print("the subtraction is : ", self.val1 - self.val2)
def multiplication(self):
print("the multiplication is : ", self.val1 * self.val2)
def devsion(self):
print("the devsion is : ", self.val1/self.val2)
obj = MyCalculator(200, 100)
obj.sumthis()
obj.subtraction()
obj.multiplication()
obj.devsion()
Output:
the sum is : 300
the subtraction is : 100
the multiplication is : 20000
the devsion is : 2.0
Destructor in Python OOP:
A destructor is a method that is automatically called when an object is about to be destroyed or deallocated.
The destructor method is named __del__ in Python.
It is used to perform any necessary cleanup tasks like closing files or releasing resources before the object is deleted from memory.
Syntax:
class ClassName:
def __del__(self):
# Cleanup code here
Example of Constructor in Python oops:
class Person:
def __init__(self, name):
self.name = name
print(f"{self.name} has been created.")
def __del__(self):
print(f"{self.name} has been deleted.")
# Creating an object of the Person class
p1 = Person("Alice")
Output:
Alice has been created.
Alice has been deleted.
22+ interview questions related to Object-Oriented Programming (OOP) concepts in Python focusing on constructors, destructors, self, attributes, and methods.
Question 1. What is a constructor in Python?
A: A constructor is a special method (__init__) that initializes an object when it's created.
Example:
class Car:
def __init__(self, model):
self.model = model
car = Car("Toyota")
print(car.model)
Output:
Toyota
Question 2. How do you define a constructor in a Python class?
A: Use the __init__ method with self as the first parameter, followed by any attributes.
Example:
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
Question 3. Can you have more than one constructor in Python?
A: Python does not support multiple constructors directly. However, you can simulate multiple constructors with default parameters or class methods.
Example:
class Car:
def __init__(self, model, year=None):
self.model = model
self.year = year if year else "Unknown"
Question 4. Why is the constructor useful?
A: The constructor initializes attributes when an object is created, ensuring that each object starts in a known state.
Question 5. What is a destructor in Python?
A: A destructor (__del__) is called when an object is about to be destroyed. It allows for cleanup before deletion.
Example:
class Car:
def __init__(self, model):
self.model = model
def __del__(self):
print(f"{self.model} is being deleted.")
car = Car("Toyota")
Output:
Toyota is being deleted.
Question 6. How do you define a destructor in Python?
A: Use the __del__ method in your class.
Example:
class Person:
def __del__(self):
print("Destructor called")
Question 7. Is the destructor called immediately after using del on an object?
A: Not necessarily. The destructor is called once all references to the object are removed, meaning it’s no longer in use.
Question 8. What is self in Python?
A: self represents the instance of the class and is used to access attributes and methods.
Example:
class Person:
def __init__(self, name):
self.name = name
Question 9. Why do we use self in class methods?
A: self allows each instance to keep track of its own data and avoid conflicts with other instances.
Question 10. Is self a keyword in Python?
A: No, it’s a convention. You could name it anything, but using self is the standard practice.
Question 11. What are attributes in Python?
A: Attributes are variables inside a class that hold data associated with the instance of the class.
Example:
class Car:
def __init__(self, color, model):
self.color = color
self.model = model
Question 12. How do you initialize attributes in Python?
A: Use the __init__ constructor with self.attribute = value.
Question 13. Can attributes be updated after an object is created?
A: Yes, you can update them directly or through methods.
Example:
class Car:
def __init__(self, color, model):
self.color = color
self.model = model
car = Car("Red", "Toyota")
car.color = "Blue"
Question 14. What is a method in Python?
A: A method is a function defined inside a class that operates on instances of the class.
Question 15. How does a method differ from a regular function?
A: A method requires self as its first parameter and is used on class instances.
Example:
class Person:
def greet(self):
print("Hello!")
p = Person()
p.greet()
Output:
Hello!
Question 16. Can you have methods with parameters in Python?
A: Yes, methods can take additional parameters.
Example:
class Calculator:
def add(self, a, b):
return a + b
calc = Calculator()
print(calc.add(2, 3))
Output:
5
Question 17. What is the difference between a constructor and a method?
A: A constructor initializes an object (with __init__), while methods perform actions on that object after it’s created.
Question 18. Give an example of using attributes in different methods within a class.
Example:
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self.balance
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
return self.balance
else:
return "Insufficient funds"
account = BankAccount("John")
print(account.deposit(100))
print(account.withdraw(50))
Output:
100
50
Question 19. What happens if you forget to use self in a method definition?
A: Python will throw an error since it expects the first argument of a method to refer to the instance (self).
Question 20. Can you create an attribute outside the constructor?
A: Yes, you can add attributes to an instance anytime, but it’s better to define essential attributes in the constructor for clarity.
Example:
class Car:
pass
car = Car()
car.color = "Red" # Adding attribute outside constructor
print(car.color)
Output:
Red
Question 21. How can you access class attributes in Python?
A: Class attributes can be accessed using ClassName.attribute or self.attribute if within a class method.
Question 22. How do you delete an attribute in Python?
A: Use del object.attribute_name to delete an attribute.
Example:
class Car:
def __init__(self, color):
self.color = color
car = Car("Red")
del car.color
Question 23. Can you have a method without self?
A: Yes, use the @staticmethod decorator to define a method that doesn’t need self.
Example:
class Math:
@staticmethod
def add(a, b):
return a + b
print(Math.add(5, 3))
Output:
8
Tags:
Leave a comment
You must be logged in to post a comment.