OOPs in Python
What is Object-Oriented Programming?
OOP stands for Object-Oriented Programming.
It is a way of writing programs by representing real-world things as software objects.
Consider a mobile phone:
- Data: brand, color, price, battery percentage
- Actions: call, charge, take a photo
In OOP:
- The data is represented using attributes
- The actions are represented using methods
- The blueprint is called a class
- The actual mobile created from that blueprint is called an object
class mobile:
def call(self):
print("calling someone.....")
phone = mobile()
phone.call()
calling someone.....
Class and Object
What is a Class?
A class is a blueprint or template used to create objects.
A house plan is not an actual house. Multiple houses can be constructed using the same plan.
Similarly, a class is a plan, and objects are the actual items created from it.
class student:
name = "Manu"
course = "GenAI"
student is a class.What is an Object?
An object is an actual instance created from a class.
student1 = student()
student2 = student()
print(student1.name)
print(student2.course)
Manu GenAI
student → classstudent1 and student2 → objectsname and course → attributes
Attributes and Methods
An attribute stores information about an object.
A method defines an action the object can perform.
class Bankaccount:
account_holder = "Sundar"
balance = 5000
def check_balance(self):
print("balance:", self.balance)
account = Bankaccount()
print(account.account_holder)
account.check_balance()
Sundar balance: 5000
Bankaccount is the classaccount is an objectaccount_holder and balance are attributescheck_balance is a method
Constructor and self
A constructor is a special method that automatically runs when an object is created from a class.
In Python, the constructor method is written as __init__().
class Employee:
def __init__(self):
print("Constructor executed")
employee1 = Employee()
Constructor executed
__init__() directly. It ran automatically when the object was created.Without Constructor
class Employee:
pass
employee1 = Employee()
employee1.name = "Prashant"
employee1.salary = 50000
With Constructor
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
employee1 = Employee("manu", 50000)
Understanding self
self represents the current object.
name and salary are constructor parameters.
self.name and self.salary are instance variables stored in the object.
When we write:
employee1 = Employee("manu", 50000)
Python internally performs something similar to:
Employee.__init__(employee1, "manu", 50000)
We do not pass a value for self. Python passes the object automatically.
Parameterized Constructor
A constructor that accepts values is called a parameterized constructor.
class Bankaccount:
def __init__(self, account_number, customer_name, balance):
self.account_number = account_number
self.customer_name = customer_name
self.balance = balance
def display_details(self):
print("Account:", self.account_number)
print("customer:", self.customer_name)
print("Balance:", self.balance)
account1 = Bankaccount(1001, "ravi", 50000)
account1.display_details()
account2 = Bankaccount(1002, "priya", 60000)
account2.display_details()
Account: 1001 customer: ravi Balance: 50000 Account: 1002 customer: priya Balance: 60000
Instance Variables
Instance variables belong to an individual object.
Each object receives its own copy of instance variables.
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
employee1 = Employee("Nandhini", 80000)
employee2 = Employee("Keerthana", 9000)
print(employee1.salary)
print(employee2.salary)
80000 9000
name and salary.Instance Methods
An instance method is a method that works with the data of a specific object.
It always takes self as the first parameter.
Most methods you write in a class are instance methods.
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def show_details(self): # Instance Method
print("Name:", self.name)
print("Salary:", self.salary)
emp1 = Employee("Ravi", 50000)
emp1.show_details()
Name: Ravi Salary: 50000
show_details is an instance method because it uses self to access the data of a particular object.
Class Methods
A class method works with the class itself, not with individual objects.
It is created using the @classmethod decorator and takes cls as the first parameter.
class Employee:
company = "KSR Datavizon" # Class Variable
def __init__(self, name, salary):
self.name = name
self.salary = salary
@classmethod
def change_company(cls, new_name):
cls.company = new_name
print("Company name changed to:", cls.company)
Employee.change_company("KSR Tech")
print(Employee.company)
Company name changed to: KSR Tech KSR Tech
Static Methods
A static method does not work with instance data (self) or class data (cls).
It is just a normal function that lives inside a class for organizational purposes.
It is created using the @staticmethod decorator.
class Calculator:
@staticmethod
def add(a, b):
return a + b
@staticmethod
def multiply(a, b):
return a * b
print(Calculator.add(10, 20))
print(Calculator.multiply(5, 6))
30 30
Single Inheritance
One child class inherits from one parent class.
class Animal:
def eat(self):
print("Eating food")
class Dog(Animal):
def bark(self):
print("Woof!")
dog = Dog()
dog.eat()
dog.bark()
Eating food Woof!
Dog inherits the eat() method from Animal.Multi-level Inheritance
A class inherits from a child class, forming a chain.
class Employee:
def attend_meeting(self):
print("Attending a meeting")
class Developer(Employee):
def write_code(self):
print("Writing code")
class seniorDeveloper(Developer):
def review_code(self):
print("Reviewing code")
senior = seniorDeveloper()
senior.attend_meeting()
senior.write_code()
senior.review_code()
Attending a meeting Writing code Reviewing code
Hierarchical Inheritance
Multiple child classes inherit from the same parent class.
class Employee:
def login(self):
print("Logged in")
class Developer(Employee):
def write_code(self):
print("Writing code")
class Manager(Employee):
def manage_team(self):
print("Managing the team")
Developer and Manager inherit login().However, a Manager does not automatically inherit
write_code() from Developer. They are separate child classes.
Multiple Inheritance
A class can inherit from more than one parent class.
class camera:
def take_photo(self):
print("Taking a photo")
class musicplayer:
def play_music(self):
print("Playing music")
class Smarthphone(camera, musicplayer):
pass
phone = Smarthphone()
phone.play_music()
phone.take_photo()
Playing music Taking a photo
Smarthphone inherits from both camera and musicplayer.Method Resolution Order (MRO)
What if both parent classes have the same method?
Python follows the Method Resolution Order (MRO).
class A:
def show(self):
print("Method from A")
class B:
def show(self):
print("Method from B")
class C(A, B):
pass
obj = C()
obj.show()
print(C.__mro__)
Method from A (<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)
Here it found
show() first in class A.
Object-Oriented Programming in Python
Classes, Objects, Constructor, Attributes, Methods and Inheritance.
Select any topic from the left sidebar to begin.
Start Learning →
