【发布时间】:2021-10-18 09:08:56
【问题描述】:
我的python版本:
python3 --version
Python 3.9.2
问题 1:isinstance函数是什么意思?
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
初始化它:
x = Singleton1()
__init__ method called, but no instance created
检查isinstance函数:
isinstance(x,Singleton1)
True
如果x不是实例,为什么isinstance(x,Singleton1)说它是Singleton1的实例?
问题2:
为什么__init__方法还是不能调用?
现在将Singleton1 类中的所有__instance(双下划线)替换为_instance(单下划线),并将所有Singleton1 替换为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
初始化它:
y = Singleton2()
instance already created: None
为什么__init__方法在这种状态下无论如何都不能调用?
@snakecharmerb on issue1,为什么有人说它是惰性实例化,如果 isinstance(x,Singleton1) 为真,则无需调用 Singleton1.get_instance() ,因为实例在实例化过程中已经创建。
【问题讨论】:
标签: python-3.x class singleton