Object-Oriented Programming (OOP) in Python
Object-Oriented Programming (OOP) is a programming approach that organizes code using classes and objects.
💡 OOP helps make programs reusable, modular, and easier to maintain.
What is a Class?
A class is a blueprint for creating objects. It defines properties (variables) and behaviors (methods).
class Student:
name = "Khushi"
age = 15
What is an Object?
An object is an instance of a class.
s1 = Student()
print(s1.name)
print(s1.age)
The __init__() Method
The __init__() method is called automatically
when an object is created.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
s1 = Student("Khushi", 15)
print(s1.name, s1.age)
The self Keyword
self refers to the current object
and is used to access variables and methods inside a class.
Class Methods
class Student:
def greet(self):
print("Hello Student!")
s = Student()
s.greet()
Inheritance
Inheritance allows one class to acquire properties of another class.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Dog barks")
d = Dog()
d.speak()
d.bark()
Practice Exercises
- Create a class for a mobile phone
- Add attributes like brand and price
- Create a method to display details