我一直在尋找在Python中Singleton設計模式在這裏:http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Singleton.html如果Python不能有私有方法那麼如何辛格爾頓工作
class OnlyOne:
class __OnlyOne:
def __init__(self, arg):
self.val = arg
def __str__(self):
return repr(self) + self.val
instance = None
def __init__(self, arg):
if not OnlyOne.instance:
OnlyOne.instance = OnlyOne.__OnlyOne(arg)
else:
OnlyOne.instance.val = arg
def __getattr__(self, name):
return getattr(self.instance, name)
我在想,在Java中,Singleton模式是使用私有實現構造函數。
但是,在上面的代碼中沒有私有構造函數,據我所知,Python中沒有私有方法。
所以如果你想實現Singleton,你怎麼能阻止某人多次實例化一個類?
在Python中,您可以覆蓋'__new__',以便在有人試圖實例化它時返回現有對象。你實際上鍊接到的一個例子就是這樣做的,儘管不是你引用的那個例子。 – khelwood
這是一個協議,你不應該直接調用諸如'__foo__'或像'__Foo'這樣的類的方法,因爲[它們被認爲是私有的](https://stackoverflow.com/questions/1641219/does-python-have -private-variables-in-classes) – CoryKramer
呃,這是python中單例的一個不好的實現。正如@ khelwood所建議的那樣,正確的方法是使用'__new__''。 –