Classes and Objects in Python: OOPS Concept

 

Classes and Objects in Python: OOPS Concept


1. Introduction to OOPS (Object-Oriented Programming System)

OOPS is a programming paradigm that is based on the concept of objects and classes. It helps in organizing complex programs by modeling real-world entities.

Key Principles of OOPS:

  1. Class: A blueprint or template for creating objects.
  2. Object: An instance of a class containing attributes (data) and methods (functions).
  3. Encapsulation: Wrapping data and methods together in a single unit (class).
  4. Inheritance: Creating new classes from existing ones.
  5. Polymorphism: Using a single interface to represent different underlying forms.
  6. Abstraction: Hiding implementation details from the user.

2. Designing Classes

A class is a blueprint for creating objects. It defines attributes and methods that its objects will have.

Syntax:

class ClassName:
    # Class attributes
    attribute1 = "value1"
    attribute2 = "value2"
    
    # Constructor (to initialize object attributes)
    def __init__(self, parameter1, parameter2):
        self.parameter1 = parameter1
        self.parameter2 = parameter2
    
    # Method
    def method_name(self):
        print("This is a method")

Example of a Class:

class Car:
    # Class Attribute
    wheels = 4

    # Constructor
    def __init__(self, brand, color):
        self.brand = brand  # Instance Attribute
        self.color = color

    # Method
    def show_details(self):
        print(f"Brand: {self.brand}, Color: {self.color}, Wheels: {self.wheels}")

# Creating an object
car1 = Car("Toyota", "Red")
car1.show_details()

car2 = Car("Honda", "Blue")
car2.show_details()

Output:

Brand: Toyota, Color: Red, Wheels: 4
Brand: Honda, Color: Blue, Wheels: 4

3. Creating Objects

An object is an instance of a class. It represents a real-world entity with properties (attributes) and behavior (methods).

Object Creation:

object_name = ClassName(arguments)

Example:

# Creating objects of the Car class
car1 = Car("Toyota", "Red")
car2 = Car("Honda", "Blue")

4. Accessing Attributes

You can access class and instance attributes using the dot (.) operator.

Example:

print(car1.brand)  # Accessing instance attribute
print(Car.wheels)  # Accessing class attribute

5. Editing Class Attributes

Class attributes can be accessed and modified using the class name or through an object.

Example:

Car.wheels = 5  # Modify class attribute
print(car1.wheels)  # Outputs: 5

6. Built-in Class Attributes

Python provides some built-in class attributes:

Attribute Description
__dict__ Dictionary containing the class's namespace.
__name__ The class name.
__module__ The module name in which the class is defined.
__bases__ Tuple of base classes (used in inheritance).

Example:

class Sample:
    pass

print("Class Name:", Sample.__name__)
print("Module Name:", Sample.__module__)
print("Bases:", Sample.__bases__)

Output:

Class Name: Sample
Module Name: __main__
Bases: (<class 'object'>,)

7. Garbage Collection

Garbage collection in Python is the process of automatically freeing memory by destroying unused objects.

  • Python uses reference counting and a garbage collector to reclaim memory.
  • The gc module provides control over garbage collection.

Destroying Objects

When an object is no longer referenced, it is automatically destroyed. The __del__ method (destructor) is called when an object is about to be destroyed.

Example:

import gc

class Example:
    def __init__(self, name):
        self.name = name
        print(f"Object {self.name} created.")

    def __del__(self):
        print(f"Object {self.name} destroyed.")

# Create an object
obj = Example("A")
del obj  # Manually delete the object

# Force garbage collection
gc.collect()

Output:

Object A created.
Object A destroyed.

8. Summary Table

Concept Description
Class A blueprint/template for creating objects.
Object An instance of a class.
Attributes Variables that store object data.
Methods Functions defined inside a class to perform actions.
Constructor (__init__) Initializes object attributes during object creation.
Destructor (__del__) Called when the object is destroyed.
Class Attributes Shared attributes across all instances of a class.
Instance Attributes Attributes specific to an object.
Garbage Collection Automatic memory management to destroy unused objects.

9. Example: Full Program

class Person:
    # Class attribute
    species = "Human"

    # Constructor
    def __init__(self, name, age):
        self.name = name  # Instance attribute
        self.age = age

    # Method to display details
    def show_details(self):
        print(f"Name: {self.name}, Age: {self.age}, Species: {Person.species}")

    # Destructor
    def __del__(self):
        print(f"Object {self.name} is destroyed.")

# Creating objects
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

# Access attributes
person1.show_details()
person2.show_details()

# Editing class attribute
Person.species = "Homo sapiens"
person1.show_details()

# Deleting objects
del person1
del person2

Output:

Name: Alice, Age: 25, Species: Human
Name: Bob, Age: 30, Species: Human
Name: Alice, Age: 25, Species: Homo sapiens
Object Alice is destroyed.
Object Bob is destroyed.

Let me know if you need further clarifications or more examples! 😊

Comments

Popular posts from this blog

Keyword , Identifier, Indentation, Comments & Documentation

DSA Lab 8 program

DSA Lab 7 Program