zoukankan      html  css  js  c++  java
  • python

    单例模式:

    class Foo:
        instance = None
        def __init__(self,name):
            self.name = name
    
        @classmethod
        def get_instance(cls):
            #cls 类名
            if cls.instance:
                return cls.instance
            else:
                obj = cls('google')
                cls.instance = obj
                return obj
    obj1 = Foo.get_instance()
    print(obj1)
    obj2 = Foo.get_instance()
    print(obj2)

    out:

    <__main__.Foo object at 0x00000000007D4278>
    <__main__.Foo object at 0x00000000007D4278>

    由上可知,obj1和obj2 内存地址都是一样的

  • 相关阅读:
    3.04
    3.03
    3.02
    3.01
    2.27
    2.25小账本6
    2.24小账本5
    2.23小账本4
    2.22小账本3
    git常用命令
  • 原文地址:https://www.cnblogs.com/pangguoping/p/5618362.html
Copyright © 2011-2022 走看看