
Python Classes and Objects-Part3
What is encapsulation?
Encapsulation is mostly about protecting data inside a class.In this we can keep data and methods together inside a single class.and we can control who can acess it
for example, without encapsulation:
class Account:
def __init__(self, balance):
self.balance = balance
a1 = Account(1000)
a1.balance = -5000 # nothing stops this, which is wrongwith encapsulation:
class Account:
def __init__(self, balance):
self._balance = balance # underscore means "internal use"
def deposit(self, amount):
self._balance = self._balance + amount
def withdraw(self, amount):
if amount > self._balance:
print("Not enough balance")
else:
self._balance = self._balance - amount
def get_balance(self):
return self._balance
a1 = Account(1000)
a1.deposit(500)
print(a1.get_balance()) # 1500
a1.withdraw(3000) # Not enough balanceNow the balance can only change through deposit and withdraw, not directly.
Why do we need encapsulation?
Because it stops wrong or invalid data from being stored, and keeps all the rules about changing the data in one place.
What is inheritance?
In a class we can use methods and properties from another class.this makes easy to use methods and properties.
for example:
class Employee:
def __init__(self, name):
self.name = name
def show(self):
print("Name:", self.name)
class Manager(Employee):
def __init__(self, name, team_size):
super().__init__(name)
self.team_size = team_size
def show_team(self):
print(self.name, "manages", self.team_size, "people")
m1 = Manager("Rohith", 8)
m1.show() # Name: Rohith (inherited from Employee)
m1.show_team() # Rahul manages 8 peopleHere, Manager is getting show() from Employee without writing it again.
What is super()?
super() is used to call the parent class's method, mostly used inside __init__ so we don't repeat the same code.
for example:
class Manager(Employee):
def __init__(self, name, team_size):
super().__init__(name) # this calls Employee's __init__
self.team_size = team_sizeWhat are parent class and child class?
- Parent class (is also called base class) = the original class
- Child class (is also called subclass) = the class that inherits from the parent
In our example:
- Employee = parent class
- Manager = child class
Can a child class have its own extra methods?
Yes. A child class can have all the parent's methods, plus its own new methods.
for example:
class Intern(Employee):
def __init__(self, name, mentor):
super().__init__(name)
self.mentor = mentor
def learn(self):
print(self.name, "is learning from", self.mentor)
i1 = Intern("Dev", "Rohith")
i1.show() # Name: Dev (inherited)
i1.learn() # Dev is learning from RohithJoin Techsnap Creators
Share your knowledge and earn ??
Want to showcase your tech expertise and get rewarded for your insights? Join the Techsnap creator network!
Write insightful blogs, stay ahead of industry trends, and grow your professional brand while helping others in the community.
Ready to make an impact?

Comments