Python : Classes and Objects

In Python, classes and objects are key concepts of object-oriented programming (OOP). They allow you to organize your code into reusable, modular units called classes, which encapsulate data (attributes) and behavior (methods). Objects are instances of classes, representing specific instances of the data and behavior defined by the class. Here's an overview of how classes and objects work in Python:

Defining a Class:


You can define a class using the class keyword followed by the class name. Inside the class definition, you can define attributes and methods.


class MyClass:
    # Constructor method (optional)
    def __init__(self, attribute1, attribute2):
        self.attribute1 = attribute1
        self.attribute2 = attribute2

    
    # Method
    def method1(self):
        return self.attribute1 + self.attribute2

 

Creating Objects (Instances):


Once a class is defined, you can create objects (instances) of that class using the class name followed by parentheses.


obj1 = MyClass(10, 20)
obj2 = MyClass(30, 40)

 

Accessing Attributes and Calling Methods:


You can access the attributes and call the methods of an object using dot notation (object_name.attribute_name or object_name.method_name() ).


print(obj1.attribute1)  # Output: 10
print(obj1.method1())   # Output: 30

 

Constructor Method (__init__):


The constructor method __init__ is called automatically when an object is created. It initializes the object's attributes.


class MyClass:
    def __init__(self, attribute1, attribute2):
        self.attribute1 = attribute1
        self.attribute2 = attribute2

 

Instance and Class Attributes:


Instance attributes are unique to each object and are defined within the constructor method (__init__). Class attributes are shared among all instances of a class and are defined outside the constructor method.


class MyClass:
    class_attribute = "Shared among all instances"
    
    def __init__(self, instance_attribute):
        self.instance_attribute = instance_attribute

 

Inheritance:


Inheritance allows you to create a new class that inherits attributes and methods from an existing class. The new class is called a subclass, and the existing class is called a superclass or base class.


class ParentClass:
    def method1(self):
        print("Parent method")

class ChildClass(ParentClass):
    def method2(self):
        print("Child method")

obj = ChildClass()
obj.method1()  # Output: Parent method
obj.method2()  # Output: Child method

 

Encapsulation, Abstraction, Polymorphism:


Classes support encapsulation (hiding the internal state of objects), abstraction (providing a simplified interface), and polymorphism (using objects of different types interchangeably).

Python's support for classes and objects allows you to write clean, modular, and maintainable code, making it easier to manage complex systems and collaborate with other developers.