Skip to main content

Posts

Showing posts with the label object-oriented design

What is a Singleton Design Pattern?

In programming, a  Singleton  is a design pattern that ensures a class has  only one instance  during the entire lifetime of a program, and provides a global access point to that instance. Singleton is widely used when you want to control resource usage, like database connections, configurations, or loading a heavy machine learning model only once. Why Use Singleton? Efficient memory usage Controlled access to a resource Ensures consistency across your application Simple Singleton Implementation in Python class SingletonMeta(type): _instances = {} def __call__(cls, *a rgs, **kwargs): if cls not in cls._instances: instance = super().__call__( *a rgs, **kwargs) cls._instances[cls] = instance return cls._instances[cls] class SingletonExample( metaclass =SingletonMeta): def __init__(self): print ( "Initializing SingletonExample" ) # Usage a = SingletonExample() b = SingletonExample() print (a is b) # T...

The Ultimate Guide to Python Classes

Introduction In Python,  classes  are the cornerstone of object-oriented programming (OOP). They allow developers to encapsulate data and functionality together, building reusable, modular, and maintainable codebases. In this guide, we will deeply explore Python classes — from basic syntax to advanced features — with fully working code examples, perfect for intermediate and advanced Python developers. What is a Python Class ? A  class  in Python is a blueprint for creating objects. It bundles data (attributes) and methods (functions) that operate on the data into one single unit. Basic Structure of a Class class ClassName: def __init__(self, parameters): self.attribute = value def method(self, parameters): # method body pass __init__()  is a special method called the  constructor , automatically invoked when creating an instance. 'self'  refers to the instance itself and must always be the first parameter in instance m...