It focuses on modeling real-world entities and their behaviors, making code modular, maintainable, and easier to understand.
Python is a fully object-oriented language β everything in Python (like strings, lists, and functions) is actually an object of some class.
What is Object-Oriented Programming?
OOP is based on the concept of grouping related data and behavior together into single units called objects. This approach promotes code reusability and scalability.OOP revolves around four key principles:
1. Encapsulation β Wrapping data and methods inside a class.
2. Abstraction β Hiding implementation details from the user.
3. Inheritance β Reusing code by deriving new classes from existing ones.
4. Polymorphism β Using a single interface for different data types.
Classes and Objects
A class is a blueprint for creating objects, and an object is an instance of a class. A class defines attributes (data) and methods (functions) that describe an object's behavior.For instance:
Class: Car (defines brand, model, engine, start/stop)
Object: Your specific car (e.g., "Tesla Model 3")
Example:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
# Creating an object
s1 = Student("Alice", 21)
print(s1.name)
print(s1.age)
init() is a special method (constructor) that initializes the object's data.self refers to the current instance of the class.
s1 is an object of the Student class.
Attributes and Methods
A class can contain two main types of components:| Component | Description |
|---|---|
| Attributes | Variables that hold object data |
| Methods | Functions that define object behavior |
class Car:
def __init__(self, brand, color):
self.brand = brand # Attribute
self.color = color # Attribute
def start(self): # Method
print(f"{self.brand} is starting...")
car1 = Car("Tesla", "Red")
car1.start()
- Attributes store information about the object.- Methods perform actions using that data.
Instance vs Class Attributes
Instance attributes are specific to each object. Class attributes are shared among all objects of a class.Example:
class Dog:
species = "Mammal" # Class attribute
def __init__(self, name):
self.name = name # Instance attribute
d1 = Dog("Bruno")
d2 = Dog("Rocky")
print(d1.species, d1.name)
print(d2.species, d2.name)
Both d1 and d2 share the same species value but have different name values.
Methods in Classes
In Python, a method is simply a function that belongs to a class. Different methods behave differently depending on what they operate on β the instance, the class, or neither.| Method Type | Description | Example Decorator | Who Receives First Argument |
|---|---|---|---|
| Instance Method | Operates on instance data | β | self (represents the current object) |
| Class Method | Operates on class data | @classmethod | cls (represents the class itself) |
| Static Method | Utility method, doesn't use class or instance data | @staticmethod | None |
class MathUtils:
# Instance Method
def add(self, a, b):
return a + b
# Class Method
@classmethod
def info(cls):
print("This is a Math utility class.")
# Static Method
@staticmethod
def greet():
print("Welcome to MathUtils!")
1. Instance Method
Needs an object to call it.Accesses instance variables (specific to that object).
calc = MathUtils() # Create object
print(calc.add(5, 3)) # Uses instance method, Output: 8
2. Class Method
Works with the class, not a specific object.Commonly used for factory methods or operations affecting all objects.
MathUtils.info() # Output: This is a Math utility class.
3. Static Method
Independent function grouped inside a class for logical organization.Doesn't access or modify object/class data.
MathUtils.greet() # Output: Welcome to MathUtils!
| Type | Decorator | First Parameter | Access to Data | When to Use |
|---|---|---|---|---|
| Instance | None | self | Instance variables | When the function works on object-specific data |
| Class | @classmethod | cls | Class variables | When the function works on data shared by all instances |
| Static | @staticmethod | None | No access | When itβs a helper/utility function related to the class |
The __init__() Constructor
The init() method automatically runs when a new object is created. It's often used to initialize object attributes.class Book:
def __init__(self, title, author):
self.title = title
self.author = author
print("Book object created!")
b1 = Book("Python 101", "John Doe")
- Each object can hold unique attribute values.- The constructor ensures every object starts with required data.
The self Keyword
self represents the instance of the class. It allows access to the object's attributes and methods.class Person:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, my name is {self.name}")
p1 = Person("Alice")
p1.greet()
Without self, methods wouldn't know which object's data to use.
Updating and Deleting Attributes
Attributes can be modified or deleted dynamically.class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
emp = Employee("Bob", 50000)
emp.salary = 55000 # Update
print(emp.__dict__)
del emp.name # Delete
print(emp.__dict__) # Shows remaining attributes
Output:
{'name': 'Bob', 'salary': 55000}
{'salary': 55000}
The dict attribute shows all data stored in the object.
Summary
Classes and objects are the foundation of Object-Oriented Programming in Python. They make it possible to build modular, reusable, and organized code that models real-world systems.| Concept | Description |
|---|---|
| Class | Blueprint or template for objects |
| Object | Instance of a class |
| Attribute | Variable that stores data for an object |
| Method | Function that defines object behavior |
| __init__() | Constructor for initializing new objects |
| self | Refers to the current instance |
| Class attribute | Shared across all instances |
| Instance attribute | Unique to each object |