page contents

类方法怎么实现单例模式

类方法怎么实现单例模式

class A(object):

    instance = None


    @classmethod

    def funa(cls):

        if A.instance is None:

            A.instance = object.__new__(A)

            #或 A.instance=object.__new__(cls)

            #或 A.instance=super().__new__(cls)

                                           

        return A.instance   # 单例模式可以不返回,只是不返回对象引用,init方法不会调用


a = A.funa()  #类名.方法名 的方法来创建实例

b = A.funa() 

print(id(a))

print(id(b))

  • 发表于 2021-09-11 22:01
  • 阅读 ( 464 )
  • 分类:Python开发

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
Wilia
Wilia

28 篇文章

作家榜 »

  1. 轩辕小不懂 2403 文章
  2. 小柒 1324 文章
  3. Pack 1135 文章
  4. Nen 576 文章
  5. 王昭君 209 文章
  6. 文双 71 文章
  7. 小威 64 文章
  8. Cara 36 文章