Python 笔记之单例

复制代码
#单例模式:只产生一次地址
#开发模式:单例模式
复制代码
class singleleton:
    #私有化当前实例(对于内存的优化,保持地址)
    #单例的地址就存在于__instance中
    __instance=None
    name='jack'
    #重写__new__
    def __new__(cls):
        print('__new__')
        if cls.__instance is None:
            print('是空')
            cls.__instance=object.__new__(cls)
            print(cls.__instance)
            return cls.__instance
        else:
            print('不是空')
            return cls.__instance
    def show(self,n):
        print('--->show {0} is {1}'.format(self.name,n))
print(dir(singleleton))#查看类中所有的attribute
s=singleleton()
s1=singleleton()
print(s)
print(s1)
s.show(5)
s1.show(7)

输出:

'__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_singleleton__instance', 'name', 'show'

new

是空

<main.singleleton object at 0x000001D38C2F7130>

new

不是空

<main.singleleton object at 0x000001D38C2F7130>

<main.singleleton object at 0x000001D38C2F7130>

--->show jack is 5

--->show jack is 7

相关推荐
kite01211 小时前
浏览器工作原理06 [#]渲染流程(下):HTML、CSS和JavaScript是如何变成页面的
javascript·css·html
крон1 小时前
【Auto.js例程】华为备忘录导出到其他手机
开发语言·javascript·智能手机
老胖闲聊2 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1182 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
曹勖之3 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
scdifsn4 小时前
动手学深度学习12.7. 参数服务器-笔记&练习(PyTorch)
pytorch·笔记·深度学习·分布式计算·数据并行·参数服务器
coding随想4 小时前
JavaScript ES6 解构:优雅提取数据的艺术
前端·javascript·es6
年老体衰按不动键盘4 小时前
快速部署和启动Vue3项目
java·javascript·vue
lyaihao4 小时前
使用python实现奔跑的线条效果
python·绘图
灵感__idea4 小时前
JavaScript高级程序设计(第5版):无处不在的集合
前端·javascript·程序员