前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python编写只允许实例化一个对象的类

Python编写只允许实例化一个对象的类

作者头像
Python小屋屋主
发布2018-04-16 17:10:43
1.6K0
发布2018-04-16 17:10:43
举报
文章被收录于专栏:Python小屋Python小屋

>>> class T: __total = 0 def __init__(self, value): if T.__total != 0: raise Exception('You can only create one instanse') self.value = value T.__total += 1

>>> t1 = T(3)

# 实例化第二个对象时出错 >>> t2 = T(5) Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> t2 = T(5) File "<pyshell#6>", line 5, in __init__ raise Exception('You can only create one instanse') Exception: You can only create one instanse

但是,由于Python对私有数据成员没有提供严格的访问控制保护机制,所以上面的代码无法避免下面的情况。

>>> T._T__total = 0 >>> t2 = T(5) >>> T._T__total = 0 >>> t3 = T(8) >>> t1 <__main__.T object at 0x0000018771177FD0> >>> t2 <__main__.T object at 0x0000018771177F98> >>> t3 <__main__.T object at 0x00000187711F8F98>

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2017-05-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Python小屋 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档