我的印象是,使用Singleton模式我可以将类的实例化数量限制为一个对象。记住这一点,看看下面的代码:
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class base1(object):
__metaclass__ = Singleton
class base2(base1):
pass
class base3(base1):
pass
class base4(base2):
pass
obj1 = base4()
obj2 = base4()
print obj1 is obj2 #prints True
obj3 = base3()
obj4 = base3()
print obj3 is obj4 #prints True
print obj1 is obj3 #prints False
第一个打印语句打印True
,证明obj3
和obj4
是同一个对象。但第二个打印语句打印False
证明obj1
和obj3
不相同。什么是实现目标的最佳方式,"Always return the same base1 object no matter which sub class instantiates it"
。
答案 0 :(得分:-1)
代码是从here复制的。
您可以创建一个terminal
类并将其用作__metaclass__
,以便其他类无法继承它:
class terminal(type):
def __init__(self, cl_name, bases, namespace):
for cls in bases:
if isinstance(cls, terminal):
raise TypeError("in "+cl_name+" definition : "+str(cls)+
" can't be used as a base class")
super(terminal, self).__init__(cl_name, bases, namespace)
# first we create a normal class
class a(object):
pass
#the terminal class: it can inherit from other classes but can't be
#used as base class
class b(a):
__metaclass__= terminal
#this will fail because inheriting from b is forbidden
class c(b):
pass