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

相关推荐
源图客几秒前
【亚马逊 SP-API 实战】Java 批量创建变体 Listing(父商品 + 子变体 + 独立图片)完整教程(亲测可用)
java·大数据·python
Cinthia10031 分钟前
学习深度学习过程中对线性代数的几何理解
python·线性代数·机器学习
Xpower 172 分钟前
Codex 桌面端更新后 Chrome 插件和 Computer Use 不可用,怎么排查和修复
前端·人工智能·chrome·python·学习
Wang ruoxi2 小时前
Pygame 小游戏——贪吃蛇
python·pygame
大数据魔法师6 小时前
Streamlit(二十三)- 教程(二)- 动态导航
python·web
心中有国也有家9 小时前
GE图引擎深度解析——CANN的计算图优化与执行引擎
人工智能·pytorch·python·学习·numpy
小陈同学呦10 小时前
前端如何处理订单状态导航的数据竞态问题
前端·javascript
开发者每周简报10 小时前
网海三部曲·无名宗师传
javascript·人工智能
卷毛的技术笔记10 小时前
告别硬编码!Spring AI Alibaba 实现 AI Agent 智能工具调用(Tool Calling)
java·人工智能·后端·python·spring·ai编程
编程大师哥10 小时前
匿名函数 lambda + 高阶函数
java·python·算法