Python OOP
Model behavior and data with classes and objects.
As programs become larger and more complex, organizing code becomes increasingly important. Writing everything in one place can make a program difficult to understand and maintain. Object-Oriented Programming (OOP) helps organize code into reusable and manageable pieces.
In Python, OOP allows you to create objects that represent real-world things such as students, cars, books, or bank accounts. Each object can have its own data and actions, making programs easier to design and expand.
In this lesson, you will learn the basics of Object-Oriented Programming, including classes, objects, constructors, inheritance, polymorphism, encapsulation, abstraction, and magic methods.
What is Object-Oriented Programming?
Object-Oriented Programming is a programming style where code is organized using classes and objects. Think of a class as a blueprint and an object as an actual item created from that blueprint.
- Class: Car
- Objects: Honda City, Tesla Model 3, BMW X5
Every car has properties such as color and model, and actions such as starting or stopping the engine. Python lets you model these real-world concepts with classes and objects.
What is a Class?
A class is a blueprint that defines the properties and behaviors of an object. Create a class using the class keyword.
class Student:
passThis creates an empty class named Student.
What is an Object?
An object is an instance of a class. Each object is created independently from the same blueprint.
class Student:
pass
student1 = Student()
student2 = Student()
print(student1)
print(student2)The __init__() Constructor
The __init__() method is a special function that runs automatically when an object is created. It is used to initialize object data.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
student = Student("Alice", 20)
print(student.name)
print(student.age)Output
Alice
20The self parameter refers to the current object and allows methods to access its data.
Instance Variables and Methods
Variables that belong to an object are called instance variables, while functions defined inside a class are called methods. Methods describe the actions an object can perform.
class Student:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, my name is {self.name}")
student = Student("John")
student.greet()Output
Hello, my name is JohnInheritance
Inheritance allows one class to use features of another class. This encourages reuse and helps avoid repeating code.
class Animal:
def speak(self):
print("Animal makes a sound.")
class Dog(Animal):
pass
dog = Dog()
dog.speak()Output
Animal makes a sound.Here, the Dog class inherits the speak() method from the Animal class.
Polymorphism
Polymorphism means different classes can provide methods with the same name but different behavior.
class Dog:
def speak(self):
print("Dog barks.")
class Cat:
def speak(self):
print("Cat meows.")
animals = [Dog(), Cat()]
for animal in animals:
animal.speak()Output
Dog barks.
Cat meows.The same speak() method call behaves differently depending on the object.
Encapsulation
Encapsulation keeps data and the methods that work with it together inside a class. It also helps protect data from being changed incorrectly.
class BankAccount:
def __init__(self, balance):
self.__balance = balance
def show_balance(self):
print(self.__balance)
account = BankAccount(5000)
account.show_balance()The double underscore indicates that the variable is intended for internal use within the class. Encapsulation helps keep data organized and discourages accidental direct access.
Abstraction
Abstraction means hiding unnecessary details and showing only essential features. When you drive a car, you use the steering wheel and pedals without needing to understand every internal engine operation.
In programming, abstraction lets users interact with objects without worrying about their internal implementation. Python supports abstraction through classes and abstract base classes.
Magic Methods
Python provides special methods called magic methods, or dunder methods, that begin and end with double underscores.
- __init__() initializes an object.
- __str__() returns a readable string representation.
- __len__() returns the length of an object.
class Book:
def __init__(self, title):
self.title = title
def __str__(self):
return self.title
book = Book("Python Basics")
print(book)Output
Python BasicsMagic methods let you customize how objects behave with Python's built-in operations.
Why Use OOP?
- Organizes code into reusable classes.
- Reduces code duplication.
- Makes programs easier to maintain.
- Simplifies large projects.
- Models real-world objects naturally.
- Encourages clean and modular design.
Most modern Python applications use OOP because it improves code organization, reuse, and scalability.
Key Takeaways
- Object-Oriented Programming organizes code using classes and objects.
- A class is a blueprint, while an object is an instance of a class.
- The __init__() constructor initializes object data when an object is created.
- Instance variables store object-specific data, and methods define object behavior.
- Inheritance allows one class to reuse features from another class.
- Polymorphism lets different classes use the same method name with different behavior.
- Encapsulation protects and organizes data within a class.
- Abstraction hides complex implementation details from users.
- Magic methods customize how objects behave.
- OOP makes Python programs cleaner, more reusable, and easier to manage as projects grow.