Python Classes and Objects

In Python, classes and objects are essential parts of Object-Oriented Programming (OOP). They help you create organized, reusable code by breaking it down into elements that reflect real-world items.

Classes

A class serves as a blueprint for making objects. It outlines a collection of attributes (data) and methods (functions) that the objects created from that class will possess.

Classes provide a means of bundling data and functionality together.

Each class instance can have attributes attached to it for maintaining its state.

Python’s class mechanism adds classes with a minimum of new syntax and semantics.

Python classes provide all the standard features of object-oriented programming

Example:


class Car:
    # Initializer or constructor to set up initial attributes
    def __init__(self, companyName, color):
        self.companyName = companyName  # attribute
        self.color = color  # attribute

    # Method
    def start(self):
        print(f"The {self.color} {self.companyName} car is starting.")

Objects

An object is an instance of a class. When you create an object, you are creating an individual item based on the class blueprint.


# Creating an object of the Car class
my_car = Car("Tata", "White")

# Accessing attributes
print(my_car.companyName)  # Output: Tata
print(my_car.color)  # Output: White

# Calling a method
my_car.start()  # Output: The White Tata car is starting.

Key Concepts

Attributes: These are the properties of an object and are defined in the __init__ method of a class.

Methods: These are functions within a class that describe how an object behaves.

Constructor (__init__method): This special method sets up the attributes of an object when it is created.

Self parameter: This refers to the instance of the class itself, allowing access to its attributes and methods.

Example of Classes and Objects


class Pet:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def get_name(self):
        return self.name

    def get_age(self):
        return self.age

# Creating an object
my_dog = Pet("Tommy", 7)

# Accessing methods
my_dog.name()         # Output: Tommy
print(my_dog.get_age())  # Output: 7

Why use class and Object?

Classes and objects are valuable for building structured, modular, and manageable code in larger programs.

Modularity: The code is more modular, making it simpler to handle.

Reusability: You can create multiple objects from one class.

Encapsulation: Classes combine data and functions, keeping them protected and organized.