Back to Study Material Python

Classes and Objects

A class in Python is defined using the class keyword followed by the class name and a colon. By convention, class names use PascalCase, meaning each word s...

Classes and Objects

Defining Classes and Creating Objects in Python

A class in Python is defined using the class keyword followed by the class name and a colon. By convention, class names use PascalCase, meaning each word starts with a capital letter. The body of the class is indented and contains method definitions and optionally class-level attributes.

The most important method in most classes is __init__, which Python calls automatically whenever you create a new object. This method is responsible for setting up the initial state of the object. It takes self as its first parameter, which refers to the newly created instance. Any additional parameters you define let you pass data in at creation time.

class Rectangle: def __init__(self, width, height): self.width = width self.height = height

def area(self): return self.width * self.height

def perimeter(self): return 2 * (self.width + self.height)

rect = Rectangle(5, 3) print(rect.area()) # 15 print(rect.perimeter()) # 16

In this example, rect is an instance of Rectangle. When you write rect.area(), Python looks up the area method on the Rectangle class and calls it, automatically passing rect as the self argument.

You can create as many objects as you like from the same class. Each one is independent. Changing rect.width does not affect any other Rectangle object you have created. This independence is one of the key advantages of OOP.

Python also supports special methods called dunder methods (short for double underscore) such as __str__ and __repr__. Defining __str__ lets you control how an object looks when printed. This makes debugging much easier because you can see meaningful output instead of raw memory addresses.

class Rectangle: def __str__(self): return f"Rectangle({self.width} x {self.height})"

Interview tip: Be ready to explain the difference between __str__ and __repr__. The __str__ method is for human-readable output, while __repr__ is meant for developers and should ideally return a string that, when passed to eval(), recreates the object.