Top 5 Python Interview Problems on Classes and Objects

2.72K 0 0 0 0

Chapter 2: Track the Number of Instances Created Using a Class Variable

🧠 Objective

To master:

  • The use of class variables (shared by all instances)
  • Tracking the total number of instances of a class
  • The difference between instance and class variables
  • Using class methods to access and return shared data

This type of question is often asked in interviews to test your understanding of object identity, scope, and lifecycle in Python classes.


📌 Problem Statement

Create a class called Person that:

  1. Has instance attributes: name, email
  2. Tracks the total number of instances created using a class variable
  3. Includes a class method to return the current instance count
  4. Uses a readable __str__() method to display the object

🔧 Step-by-Step Implementation


Step 1: Define the Class and Class Variable

class Person:

    total_instances = 0  # class variable

This variable is shared across all instances and will increment every time a new object is created.


Step 2: Initialize and Track Count in __init__

    def __init__(self, name, email):

        self.name = name

        self.email = email

        Person.total_instances += 1

Use the class name Person.total_instances to access and increment the class-level count.


Step 3: Add a Class Method to Retrieve Count

    @classmethod

    def get_instance_count(cls):

        return cls.total_instances

This method is bound to the class, not the instance — note the use of cls instead of self.


Step 4: Add __str__ for Readability

    def __str__(self):

        return f"Person(name={self.name}, email={self.email})"


Full Working Code

class Person:

    total_instances = 0  # shared across all objects

 

    def __init__(self, name, email):

        self.name = name

        self.email = email

        Person.total_instances += 1

 

    @classmethod

    def get_instance_count(cls):

        return cls.total_instances

 

    def __str__(self):

        return f"Person(name={self.name}, email={self.email})"


🧪 Example Usage

p1 = Person("Alice", "alice@example.com")

p2 = Person("Bob", "bob@example.com")

p3 = Person("Charlie", "charlie@example.com")

 

print(p1)

print(p2)

print(p3)

 

print("Total instances created:", Person.get_instance_count())


Output:

Person(name=Alice, email=alice@example.com)

Person(name=Bob, email=bob@example.com)

Person(name=Charlie, email=charlie@example.com)

Total instances created: 3


🔁 Class vs Instance Variable Comparison Table

Feature

Class Variable (total_instances)

Instance Variable (name, email)

Scope

Shared across all objects

Unique to each object

Declared

Outside __init__, inside class

Inside __init__

Accessed via

ClassName.var or cls.var

self.var

Typical use

Counters, config, constants

Object-specific data


🧠 Adding More Features

🔹 Count Active vs Deleted Instances

def __del__(self):

    Person.total_instances -= 1

Use this to reduce the count when an object is deleted.
️ Caution: __del__() is not always reliable in production (GC timing varies).


🔹 Count Instances Per Subclass (Advanced)

Use cls.__name__ inside the class method to track instances of subclasses individually.


Summary Table

Feature

Purpose

@classmethod

Bind method to class, not instance

cls

Represents class (like self does for object)

Class variable

Tracks info shared across instances

Person.total_instances

Increments in constructor



Back

FAQs


1. What is a class in Python?

A class is a blueprint for creating objects. It defines attributes (variables) and methods (functions) that describe the behavior of the objects.

2. What is the difference between class variables and instance variables?

Class variables are shared across all instances of a class, whereas instance variables are unique to each object.

3. How does __init__() work in a class?

__init__() is the constructor method in Python that gets called automatically when a new object is instantiated.

4. What’s the difference between __str__() and __repr__()?

__str__() returns a user-friendly string representation of the object, while __repr__() returns a more technical, unambiguous string for developers.

5. How is inheritance implemented in Python classes?

Python allows a class to inherit from another using (BaseClassName) syntax. The child class gets access to the parent’s attributes and methods.

6. What is encapsulation in Python?

Encapsulation is restricting direct access to some of an object’s components. This is done using private attributes and getter/setter methods.

7. Can a class in Python have multiple constructors?

Python does not support multiple __init__ methods. However, you can use default arguments or @classmethod to simulate multiple constructors.

8. What is polymorphism in OOP with Python?

Polymorphism allows methods to have the same name but behave differently depending on the class or object calling them

9. How are objects and instances different in Python?

There's no real difference. "Object" and "instance" are often used interchangeably. An object is an instance of a class.