(七)python 设计模式 --- 单例模式

# -*- coding: utf-8 -*-


class Singleton(object):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            print('create new')
            cls._instance = super(Singleton, cls).__new__(cls)
        else:
            print('use created')
        return cls._instance

    def __del__(self):
        print('del')
        del self


class MyClass(Singleton):
    def __init__(self, name):
        self.name = name
  • __ new __方法, 是python中类实例的构造方法,将一个类的实例绑定到类变量_instance上,
  • 如果cls._instance为None说明该类还没有实例化过,实例化该类,并返回
  • 如果cls._instance不为None,直接返回cls._instance
    -运行结果如下:
create new
Lee 657950027168
use created
AngelovLee 657950027168
del
    原文作者:AngelovLee
    原文地址: https://blog.csdn.net/changerjjlee/article/details/82454800
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞