Python OOPs Concepts¶
Object-Oriented Programming (OOP)¶
OOP is a programming paradigm based on the concept of "objects", which can contain data and code.
Key Concepts¶
- Class: A blueprint or template for creating objects. (e.g., The blueprint for a Car).
- Object: An instance of a class. (e.g., Your specific red Toyota is an object of the Car class).
- Encapsulation: Hiding the internal details of how an object works and only showing what is necessary. (e.g., You press the gas pedal, you don't need to know how the fuel injection works).
- Inheritance: Creating a new class based on an existing one. (e.g., An "Electric Car" inherits features from a "Car").
- Polymorphism: The ability of different objects to respond to the same command in their own way. (e.g., Both a "Car" and a "Bicycle" have a
move()method, but they move differently). - Abstraction: Focusing on what an object does instead of how it does it. (e.g., Using a TV remote without knowing the electronics inside).
Logic First
OOP helps us model the real world in code. It makes large programs easier to maintain, reuse, and scale.
Why use OOP in Python?¶
Python is an object-oriented programming language. Almost everything in Python is an object, with its properties and methods.
OOP allows you to: - Reuse code: Through inheritance. - Maintain code: Easier to fix a bug in a class than in 100 separate functions. - Security: Protect data through encapsulation.
Real-World Example in Python¶
Imagine we are building a school management system. Instead of having separate lists for names, ages, and grades, we can create a Student class.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def study(self):
print(f"{self.name} is studying...")
Now, every time we have a new student, we just create a new Object from this blueprint!