(七)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

你可能感兴趣的:(Python开发,python高级编程)