Introduction To OOP Lesson008
Introduction To OOP Lesson008
def bark(self):
print("Woof!")
Destructors
A destructor is automatically called when an object is about to be destroyed. It's
defined using the __del__ method. It's often used for cleanup tasks, like releasing
resources. However, Python's garbage collection usually handles memory
management, reducing the need for explicit destructors.
class Dog:
def __init__(self, name):
self.name = name
print(f"{self.name} created")
def __del__(self):
print(f"{self.name} destroyed")
my_dog = Dog("Buddy")
del my_dog
# Output:
# Buddy created
# Buddy destroyed
Usage
Constructors are essential for setting up objects, while destructors are less
commonly used in Python due to automatic garbage collection. Destructors are
useful in situations where external resources need to be released explicitly.
def display(self):
print("Name:", self.name)
print("Age:", self.age)
s = Student("John", 20)
s.display()
Output
Name: John
Age: 20
def __display_balance(self):
print("Balance:", self.__balance)
b = BankAccount(1234567890, 5000)
b.__display_balance() # Trying to access private method
output
AttributeError: 'BankAccount' object has no attribute '__display_balance'
Why Does This Error Happen
Because of Python’s name mangling for private members.
When you define a method or variable with two leading underscores like
__display_balance, Python internally renames it to make it harder to access from
outside the class.
__display_balance --> _BankAccount__display_balance
This is done to:
Prevent accidental access or modification of private members.
Avoid name conflicts in subclasses.
def _display(self):
print("Name:", self._name)
print("Age:", self._age)
class Student(Person):
def __init__(self, name, age, roll_number):
super().__init__(name, age)
self._roll_number = roll_number
def display(self):
self._display()
print("Roll Number:", self._roll_number)
s = Student("John", 20, 123)
s.display()
output
Name: John
Age: 20
Roll Number: 123