My python version:
python3 --version
Python 3.9.2
Issue 1:
What does isinstance
function mean?
class Singleton1(object):
__instance = None
def __init__(self):
if not hasattr(Singleton1, '__instance'):
print("__init__ method called, but no instance created")
else:
print("instance already created:", self.__instance)
@classmethod
def get_instance(cls):
if not cls.__instance:
cls.__instance = Singleton1()
return cls.__instance
Initialize it :
x = Singleton1()
__init__ method called, but no instance created
Have a check with isinstance
function:
isinstance(x,Singleton1)
True
If x is not an instance,why does isinstance(x,Singleton1)
say it is an instance of Singleton1?
Issue2:
Why __init__
method can't be called anyway?
Now repalce all __instance
(double underscores) with _instance
(single underscore) in the class Singleton1
and replace all Singleton1
with Singleton2
:
class Singleton2(object):
_instance = None
def __init__(self):
if not hasattr(Singleton2, '_instance'):
print("__init__ method called, but no instance created")
else:
print("instance already created:", self._instance)
@classmethod
def get_instance(cls):
if not cls._instance:
cls._instance = Singleton2()
return cls._instance
Initialize it:
y = Singleton2()
instance already created: None
Why __init__
method can't be called anyway in this status?
@snakecharmerb on issue1,Why someone say it is lazy instantiation ,if isinstance(x,Singleton1) is true,it is no need to call with Singleton1.get_instance() ,because the instance is already created during instantiation.