注:使用的是Python 2.7。
一個簡單實現
代碼如下:
class Foo(object):
__instance = None
def __init__(self):
pass
@classmethod
def getinstance(cls):
if(cls.__instance == None):
cls.__instance = Foo()
return cls.__instance
if __name__ == '__main__':
foo1 = Foo.getinstance()
foo2 = Foo.getinstance()
print id(foo1)
print id(foo2)
print id(Foo())
輸出的前兩個結果是相同的(id(foo1)與id(foo2)的值相同),第三個結果和前兩個不同。這里類方法getinstance()用于獲取單例,但是類本身也可以實例化,這樣的方式其實并不符合單例模式的要求。但是這樣做也有好處,代碼簡單,大家約定好這樣子調用就行了。但是最好在類的命名上也體現了出來這是一個單例類,例如Foo_singleton。
換一個思路
先說一下init和new的區別:
代碼如下:
class Foo(object):
__instance = None
def __init__(self):
print 'init'
if __name__ == '__main__':
foo = Foo()
運行結果是:
代碼如下:
init
而下面的示例:
代碼如下:
class Foo(object):
__instance = None
def __init__(self):
print 'init'
def __new__(cls, *args, **kwargs):
print 'new'
if __name__ == '__main__':
foo = Foo()
運行結果是:
代碼如下:new
new是一個類方法,會創建對象時調用。而init方法是在創建完對象后調用,對當前對象的實例做一些一些初始化,無返回值。如果重寫了new而在new里面沒有調用init或者沒有返回實例,那么init將不起作用。以下內容引用自http://docs.python.org/2/reference/datamodel.html#object.new
代碼如下:
If __new__() returns an instance of cls, then the new instance's __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__().
If __new__() does not return an instance of cls, then the new instance's __init__() method will not be invoked.
這樣做:
代碼如下:
class Foo(object):
__instance = None
def __init__(self):
print 'init'
def __new__(cls, *args, **kwargs):
print 'new'
if cls.__instance == None:
新聞熱點
疑難解答