class MyClass:
def __new__(cls,**wargs):
if "create" in wargs: # This is just an example, obviously
if wargs["create"] >0: # you can use any test here
# The point here is to "forget" to return the following if your
# conditions aren't met:
return super(MyClass,cls).__new__(cls)
return None
def __init__(self,**wargs): # Needs to match __new__ in parameter expectations
print ("New instance!")
a=MyClass() # a = None and nothing is printed
b=MyClass(create=0) # b = None and nothing is printed
c=MyClass(create=1) # b = <__main__.MyClass object> and prints "New instance!"
def SingletonClass(cls):
class Single(cls):
__doc__ = cls.__doc__
_initialized = False
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Single, cls).__new__(cls, *args, **kwargs)
return cls._instance
def __init__(self, *args, **kwargs):
if self._initialized:
return
super(Single, self).__init__(*args, **kwargs)
self.__class__._initialized = True # Its crucial to set this variable on the class!
return Single
使用:
而不是
^{pr2}$参见abort instance creation,尤其是new and init的公认答案
编辑:我添加了我自己的以下代码,作为它如何工作的一个简单示例-在实际场景中,您需要的不仅仅是这些:
在实例创建之前,
__new__
被称为,与__init__
不同的是,它返回一个值-该值是实例。有关更多信息,请参阅上面的第二个链接-这里有一些代码示例,可以借用其中一个:相关问题 更多 >
编程相关推荐