OOP Concepts
Core Object-Oriented Programming concepts for Django development.
Object-Oriented Programming (OOP) is crucial for working with frameworks like Django and Django REST Framework. You will frequently extend or overwrite existing classes and methods.
Classes and Objects
A class is a blueprint for creating objects. An object is an instance of a class.
Inheritance
Allows a new class (child) to inherit attributes and methods from an existing class (parent). This is heavily used in Django's models and views.
Polymorphism
Allows methods to do different things based on the object it is acting upon. A common use is method overriding, where a child class provides its own implementation of a parent's method.
Example of Inheritance in Django
from django.db import models
# Parent class
class BaseModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True # This model won't be created in the database
# Child class inheriting from BaseModel
class Product(BaseModel):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
def __str__(self):
# Overriding the default string representation
return self.name