#
# py_singleton.py
# py_learn
#
# Created by Z. Steve on 2023/8/8 09:45.
#
# # 查看对象地址 demo
# class Utility:
# pass
#
#
# u1 = Utility()
# u2 = Utility()
#
# # 输出发现 u1 、 u2 两个对象的地址不一样
# print(u1)
# print(id(u1))
# print(u2)
# print(id(u2))
# 单例模式
class Utility:
def say_hello(self):
print("hello world.")
# 其他地方需要使用 Utility 类的对象时,通过调用 tool 属性就永远获取的是同样的对象
tool = Utility()
#
# py_singleton_test.py
# py_learn
#
# Created by Z. Steve on 2023/8/8 10:01.
#
import py_singleton
utility = py_singleton.tool
utility2 = py_singleton.tool
utility.say_hello()
utility2.say_hello()
print(utility)
print(id(utility))
print(utility2)
print(id(utility2))
标签:singleton,Python,py,模式,单例,print,utility,id,Utility
From: https://www.cnblogs.com/zxhoo/p/17613459.html