class ExpressQuery:
# 定义类属性记录单例对象引用
_instance = None
# 创建单例
def __new__(cls):
# 1. 判断类属性是否已经被赋值
if cls._instance is None:
cls._instance = super(ExpressQuery, cls).__new__(cls)
# 2. 返回类属性的单例引用
return cls._instance
def __init__(self):
self.host = 'https://wuliu.market.alicloudapi.com' # 阿里云接口url前缀
# 个人code,获取连接 https://market.console.aliyun.com/imageconsole/index.htm
# 购买连接 https://market.aliyun.com/products/56928004/cmapi021863.html
self.app_code = ''
代码运行时候首先运行__new__方法,再运行__init__,运行__new__的时候判断是否已有实例对象,已有则不再创建,继续使用,没有的情况下则新建
测试:
express = ExpressQuery()
a = ExpressQuery()
b = ExpressQuery()
print(id(a))
print(id(b))
print(id(express))
```
来源:https://blog.csdn.net/weixin_42345642/article/details/100972528