All Questions From This Chapter « Previously Next »
can you explain this line by line in layman terms:
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class Database(metaclass=SingletonMeta):
pass
db1 = Database()
db2 = Database()
assert db1 is db2
Yes — this code is a Singleton pattern, which means it makes sure only one object of a class is ever created.
Here is the line-by-line meaning in simple terms:
Pythonclass SingletonMeta(type):
This creates a custom metaclass.
A metaclass is like a “class for classes” — it controls how classes behave when they are created or called.
Python_instances = {}
This is a dictionary used to store created objects.
It keeps track of whether an object for a class has already been made.
Pythondef __call__(cls, *args, **kwargs):
This defines what happens when you do something like Database().
Normally, calling a class creates a new object. Here, we are changing that behavior.
-
clsmeans the class being called, likeDatabase -
*argsand**kwargsmean any arguments passed to the class
Pythonif cls not in cls._instances:
This checks: “Has an object of this class already been created?”
-
If not, create one
-
If yes, reuse the old one
Pythoncls._instances[cls] = super().__call__(*args, **kwargs)
This creates the object in the normal way and stores it in _instances.
So the first time you call Database(), it makes a real object and saves it.
Pythonreturn cls._instances[cls]
This returns the stored object every time.
So after the first creation, every later call gives back the same object.
Pythonclass Database(metaclass=SingletonMeta):
This creates a class called Database, but instead of using the normal class behavior, it uses SingletonMeta.
That means Database() will follow the singleton rule.
Pythonpass
This means the class has no extra code inside it right now.
Pythondb1 = Database()
db2 = Database()
Both lines try to create a Database object.
But because of the singleton logic:
-
db1gets the first and only object -
db2gets the same exact object, not a new one
Pythonassert db1 is db2
This checks whether db1 and db2 are literally the same object in memory.
is means “same object”, not just “same value”.
This assertion passes because both variables point to the same singleton instance.
In plain English:
This code says:
“No matter how many times someone tries to create a Database, always return the same one.”
A simple real-life example is a printer service, config manager, or database connection manager where you want only one shared instance.
All Questions From This Chapter « Previously Next »
Tags: Python,Algorithms,
