Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
🧠 Objective
To master:
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:
🔧 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 |
A class is a blueprint for creating objects. It defines attributes (variables) and methods (functions) that describe the behavior of the objects.
Class variables are shared across all instances of a class, whereas instance variables are unique to each object.
__init__() is the constructor method in Python that gets called automatically when a new object is instantiated.
__str__() returns a user-friendly string representation of the object, while __repr__() returns a more technical, unambiguous string for developers.
Python allows a class to inherit from another using (BaseClassName) syntax. The child class gets access to the parent’s attributes and methods.
Encapsulation is restricting direct access to some of an object’s components. This is done using private attributes and getter/setter methods.
Python does not support multiple __init__ methods. However, you can use default arguments or @classmethod to simulate multiple constructors.
Polymorphism allows methods to have the same name but behave differently depending on the class or object calling them
There's no real difference. "Object" and "instance" are often used interchangeably. An object is an instance of a class.
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)