🐍 Python Tutorial: Object-Oriented Programming
Object-Oriented Programming (OOP) is a paradigm in Python where code is organized around objects, which are instances of classes. This allows for encapsulation, abstraction, inheritance, and polymorphism—key principles that help structure complex software systems.
1. Classes and Objects
A class is a blueprint for creating objects. An object is an instance of a class.
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(f"{self.name} says woof!")
d = Dog("Buddy")
d.bark()2. The __init__ Method
The __init__ method is a special constructor that runs when a new object is created. It initializes the object's attributes.
3. Encapsulation
Encapsulation refers to bundling data and methods that operate on the data within a class, restricting direct access to some of the object’s components.
class BankAccount:
def __init__(self, balance):
self.__balance = balance # private attribute
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance4. Inheritance
Inheritance allows one class (child) to inherit attributes and methods from another class (parent).
class Animal:
def speak(self):
print("Animal speaks")
class Cat(Animal):
def speak(self):
print("Meow")
c = Cat()
c.speak()5. Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables methods to behave differently based on the calling object.
class Bird:
def fly(self):
print("Bird flies")
class Airplane:
def fly(self):
print("Airplane flies")
def lets_fly(thing):
thing.fly()
b = Bird()
a = Airplane()
lets_fly(b)
lets_fly(a)6. Class vs Instance Attributes
Class attributes are shared across all instances, while instance attributes are unique to each instance.
class Car:
wheels = 4 # class attribute
def __init__(self, color):
self.color = color # instance attribute
c1 = Car("red")
c2 = Car("blue")
print(c1.wheels, c2.color)