What is Object-Oriented Programming?
Object-Oriented Programming, commonly called OOP, is a programming approach based on objects and classes.
Python supports object-oriented programming and allows us to create reusable and organized code.
• Class
• Object
• Attributes
• Methods
1. Class
A class is a blueprint or template for creating objects.
class Student:
pass
Here, Student is a class.
2. Object
An object is an instance of a class.
class Student:
pass
student1 = Student()
print(student1)
Here, student1 is an object
of the Student class.
3. Attributes
Attributes are variables that belong to an object or class.
class Student:
name = "Sudhanshu"
age = 18
student1 = Student()
print(student1.name)
print(student1.age)
Sudhanshu 18
4. Methods
A method is a function defined inside a class.
class Student:
def greet(self):
print("Hello!")
student1 = Student()
student1.greet()
Hello!
5. __init__() Method
The __init__() method is
automatically called when an object is created.
It is commonly used to initialize object attributes.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
student1 = Student("Sudhanshu", 18)
print(student1.name)
print(student1.age)
Sudhanshu 18
6. Practical Example
Let's create a simple class for a bank account.
class BankAccount:
def __init__(self, name, balance):
self.name = name
self.balance = balance
def show_balance(self):
print("Account Holder:", self.name)
print("Balance:", self.balance)
account = BankAccount("Rahul", 5000)
account.show_balance()
Account Holder: Rahul Balance: 5000
7. Advantages of OOP
Reusability
Classes and objects can be reused in different parts of a program.
Organization
Large programs can be divided into organized classes.
Maintainability
Code becomes easier to update and maintain.
Class → Blueprint
Object → Instance of a class
Attribute → Data of an object
Method → Function inside a class
Quick Quiz
What is a class in Python?
Finished this lesson?