Fundamentals 6 min read

Master Python’s id() and Build a Singleton Pattern

This article explains how Python’s id() function reveals an object’s memory address, demonstrates its output with simple class instances, and guides you through implementing a singleton pattern using __new__ to ensure a class has only one shared instance.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python’s id() and Build a Singleton Pattern

Preface

Beyond the real world, the network world is bustling, with the CPU working nonstop. Two characters, c and d, represent Python objects instantiated from an Animal class.

# Define an Animal class
class Animal():
    pass

cat = Animal()  # c
dog = Animal()  # d

Memory Address

Using Python’s built‑in id() function, we can retrieve the memory address of an object, which is unique for each existing object.

# Define an Animal class
class Animal():
    pass

cat = Animal()
 dog = Animal()
print('c address:', id(cat))
print('d address:', id(dog))

The output shows different addresses for cat and dog, confirming that each instance occupies a distinct memory location.

Singleton Pattern

A singleton ensures a class has only one instance and provides a global access point. In Python, we can achieve this by overriding the __new__ method.

# Define an Animal class
class Animal():
    __instance = None

    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = object.__new__(cls)
            return cls.__instance
        else:
            return cls.__instance

cat = Animal()
dog = Animal()
print('c address:', id(cat))
print('d address:', id(dog))

Both cat and dog now share the same memory address, demonstrating the singleton effect.

Singleton Pattern Effects

Advantages

Instance control – prevents creation of multiple copies, ensuring a single shared instance.

Flexibility – the class can modify the instantiation process as needed.

Disadvantages

Overhead – each request checks for an existing instance, which can add slight cost.

Potential confusion – developers must remember not to use new directly for singleton classes.

Object lifecycle – singletons may retain references, complicating memory management in some languages.

Choose the singleton pattern only when its benefits align with your design requirements.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

object‑oriented programmingsingleton patternmemory addressid function
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.