Python单例

单例简介

单例是一种开发模式。
单例指单个对象。

对象地址空间

cat singleton.py 
#!/usr/bin/env python3
#coding:utf8
class Student:
   pass
s=Student()
s1=Student()
print(s)
print(s1)

可以看到这两个对象的地址是不一样的,内存为每个对象分配一个独立的空间。使用单例模式可以让对象使用一个内存地址空间。

[root@ceph01 python]# python singleton.py 
<__main__.Student instance at 0x7fe52003a200>
<__main__.Student instance at 0x7fe52003a1b8>

真正为对象开辟内存由
return object.init()决定,通过阻止这个操作,可以让新对象不开辟新的地址。

单例实现

cat singleton.py 
#!/usr/bin/env python3
#coding:utf8
class Singleton:
   #私有化
   __instance = None
   #帮类开辟空间的函数是__new__
   #重写父类,修改__new__方法
   #cls指当前类
   def __new__(cls):
      print('------>__new__')
      if cls.__instance is None:
         cls.__instance = object.__new__(cls)
         return cls.__instance
      else: 
         return cls.__instance
s=Singleton()
s1=Singleton()
print(s)
print(s1)
python3 singleton.py 
------>__new__
------>__new__
<__main__.Singleton object at 0x7fd5028bc0b8>
<__main__.Singleton object at 0x7fd5028bc0b8>
cat singleton.py 
#!/usr/bin/env python3
#coding:utf8
class Singleton:
   #私有化
   __instance = None
   #帮类开辟空间的函数是__new__
   #重写父类,修改__new__方法
   #cls指当前类
   def __new__(cls):
      print('------>__new__')
      if cls.__instance is None:
         print("进到了if")
         cls.__instance = object.__new__(cls)
         return cls.__instance
      else:
         print("进到了else")
         return cls.__instance
s=Singleton()
s1=Singleton()
s2=Singleton()
print(s)
print(s1)
print(s2)
python3 singleton.py 
------>__new__
进到了if
------>__new__
进到了else
------>__new__
进到了else
<__main__.Singleton object at 0x7f9053724048>
<__main__.Singleton object at 0x7f9053724048>
<__main__.Singleton object at 0x7f9053724048>

简化下

cat  singleton.py 
#!/usr/bin/env python3
#coding:utf8
class Singleton:
   #私有化
   __instance = None
   #帮类开辟空间的函数是__new__
   #重写父类,修改__new__方法
   #cls指当前类
   def __new__(cls):
      print('------>__new__')
      if cls.__instance is None:
         cls.__instance = object.__new__(cls)
      return cls.__instance
s=Singleton()
s1=Singleton()
s2=Singleton()
print(s)
print(s1)
print(s2)
python3 singleton.py 
------>__new__
------>__new__
------>__new__
<__main__.Singleton object at 0x7f4fbac260b8>
<__main__.Singleton object at 0x7f4fbac260b8>
<__main__.Singleton object at 0x7f4fbac260b8>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

时空无限

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值