Skip to Content
Learning Python Design Patterns - Second Edition - Second Edition
book

Learning Python Design Patterns - Second Edition - Second Edition

by Chetan Giridhar, Gennadiy Zlobin
February 2016
Beginner to intermediate
164 pages
3h 25m
English
Packt Publishing
Content preview from Learning Python Design Patterns - Second Edition - Second Edition

Lazy instantiation in the Singleton pattern

One of the use cases for the Singleton pattern is lazy instantiation. For example, in the case of module imports, we may accidently create an object even when it's not needed. Lazy instantiation makes sure that the object gets created when it's actually needed. Consider lazy instantiation as the way to work with reduced resources and create them only when needed.

In the following code example, when we say s=Singleton(), it calls the __init__ method but no new object gets created. However, actual object creation happens when we call Singleton.getInstance(). This is how lazy instantiation is achieved.

class Singleton: __instance = None def __init__(self): if not Singleton.__instance: print(" __init__ method ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering Python Design Patterns - Second Edition

Mastering Python Design Patterns - Second Edition

Kamon Ayeva, Sakis Kasampalis
Advanced Python Programming

Advanced Python Programming

Dr. Gabriele Lanaro, Quan Nguyen, Sakis Kasampalis

Publisher Resources

ISBN: 9781785888038Supplemental Content