Object Oriented Programming Concepts

Classes and Objects

Classes and objects are fundamental concepts in Object-Oriented Programming (OOP).

A class is a template or blueprint from which objects are created. It defines the nature of future objects, representing a set of properties or methods that are common to all objects of that type. Two key components of a class are:

  • Attributes or Properties: Data that stored inside variables of an object. They hold information about the object.
  • Methods: Functions that define the behavior of class objects. Simply, they define what an object can do.

An object is an instance of a class. It is a self-contained entity that consists of both data and functionality to model real-world entities in a programming context.

Important Characteristics of an instance are:

  • Identity: A unique identifier distinguishing it from other objects.
  • State: Defined by the values of an object's attributes/properties.
  • Behavior: Determined by how the object's methods/functions are implemented.

Consider a car in real world. Each car (object) has an identity (plate number), state (color, model), and behavior (drive, brake).

An Example

Consider a simple program involving a Book class and its instances:

  • Class Definition:

    class Book:
        def __init__(self, title, author):
            self.title = title
            self.author = author
    
        def get_details(self):
            return print(f"{self.title} by {self.author}")
  • Creating Objects:

    book1 = Book("1984", "George Orwell")
    book2 = Book("To Kill a Mockingbird", "Harper Lee")
  • Using Methods:

    book1.get_details()  # Outputs: 1984 by George Orwell
    book2.get_details()  # Outputs: To Kill a Mockingbird by Harper Lee

In this example:

  • Book Class: Blueprint with title and author as attributes, and get_details as a method.
  • Objects: book1 and book2 are instances of the Book class, each with its own identity and state.
  • Method Usage: get_details method is called on each book object to retrieve its details.

Think of a class as a recipe, and an object as the dish made from that recipe. The recipe (class) can be used to make multiple dishes (objects), each with its own specific characteristics like ingredients (attributes) and preparation steps (methods).

Classes provide a way to bundle data and functionality together. Creating instances of these classes (objects) allows for the implementation of data structures and behaviors defined in the class.

Concept Description Example
Classes Blueprints for creating objects. Defines data and methods. class Car: ...
Objects Instances of classes. Represent real-world entities. my_car = Car("Tesla Model 3", "Red")
Attributes Variables within a class. Define properties of objects. model, color in Car class
Methods Functions within a class. Define behavior of objects. display_info() in Car class