1. 程式人生 > >python中對單例模式的理解

python中對單例模式的理解

name none 實例 pan 理解 proc span pytho 相等

class Foo(object):
    instance = None

    def __init__(self):
        pass
    def process(self):
        return 1234565

    @classmethod   #版本1單例模式
    def get_instance(cls):
        if  Foo.instance:
            return Foo.instance
        else:
            Foo.instance = Foo()
            return
Foo.instance obj1 = Foo() print(obj1.process()) obj2 = Foo() print(obj2.process()) obj1不相等obj2 id(obj1) obj1 = Foo.get_instance() obj2 = Foo.get_instance() 此時的obj1=obj2 class Foo(object): instance = None def __init__(self): self.name = alex def __new__(cls, *args, **kwargs):
if Foo.instance: return Foo.instance else: obj = object.__new__(cls, *args, **kwargs) #創建對象的本質是new new先執行 return return obj obj1 = Foo() obj2 = Foo() print(id(obj1), id(obj2)) obj1=obj2 單例模式2 高級版 永遠用一個對象的實例! 創建的對象內部封裝的值是一樣的 就搞成單例模式

python中對單例模式的理解