python设计模式实例(单例模式1)

1. 例子使用 Python3.6 实现

# -*- coding: utf-8 -*-
'''
Author :  www.oldpai.com
Date : 2018/5/20
Desc :1. 只允许Singleton 类生成一个实例 2. 如果已经有一个实例了,会重复提供同一个实例
'''

class Singleton(object):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls,'instance'):
            cls.instance = super(Singleton, cls).__new__(cls)
        return cls.instance

s1 = Singleton()
print("实例s1内存地址:",s1)
s2 = Singleton()
print("实例s1内存地址:",s2)

这里写图片描述

2.  __new__函数回顾
#_new__函数使用:新式类,是在init函数之前进行执行,默认的静态方法
# cls当前需要实例化的类

def __new__(cls, *args, **kwargs):
    pass

自己学习过程中作为笔记使用,如果错误欢迎大家指出,谢谢。

猜你喜欢

转载自blog.csdn.net/cjh365047871/article/details/80385921