Home → Lessons → Object-Oriented Programming

Object-Oriented Programming

Learn the basics of classes, objects, attributes and methods in Python.

Lesson 10 Beginner 25 min

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.

Basic OOP Concepts:

• Class
• Object
• Attributes
• Methods

1. Class

A class is a blueprint or template for creating objects.

Example
class Student:
    pass

Here, Student is a class.

2. Object

An object is an instance of a class.

Creating an Object
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.

Example
class Student:

    name = "Sudhanshu"
    age = 18

student1 = Student()

print(student1.name)
print(student1.age)
Output:
Sudhanshu
18

4. Methods

A method is a function defined inside a class.

Example
class Student:

    def greet(self):
        print("Hello!")

student1 = Student()

student1.greet()
Output:
Hello!

5. __init__() Method

The __init__() method is automatically called when an object is created.

It is commonly used to initialize object attributes.

Example
class Student:

    def __init__(self, name, age):
        self.name = name
        self.age = age

student1 = Student("Sudhanshu", 18)

print(student1.name)
print(student1.age)
Output:
Sudhanshu
18

6. Practical Example

Let's create a simple class for a bank account.

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()
Output:
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.

Remember:

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?