|
楼主 |
发表于 2021-10-21 21:32:20
|
显示全部楼层
- #单例,类可以定义很多个实例,继承了单例的类,就只能实例化一个对象
- class Singleton(object):
- def __new__(cls, *args, **kw):
- if not hasattr(cls, '_instance'):
- orig = super(Singleton, cls)
- cls._instance = orig.__new__(cls, *args, **kw)
- return cls._instance
- #redis的客户端类,继承单例类,所以只能有一个对象实例
- class RedisClient(Singleton):
- #__init__就是构建函数
- #类:有构建函数__init__和析构函数(pyhton一般用不到)
- def __init__(self):
- #pool连接池,创建一个127.0.0.1的redis连接,端口号6379
- #一个tcp连接需要有ip和端口号,
- #127.0.0.1本地的IP地址或者localhost也可以
- #decode_responses自动解析字符串
- self.pool = redis.ConnectionPool(
- host='127.0.0.1', port=6379, db=0, decode_responses=True
- )
- #定义该函数为只读
- @property
- def conn(self):#类里的函数,这个函数是用来获取连接的
- if not hasattr(self, '_conn'):#看这个类中有没有_conn这个参数
- self.getConnection() #调用函数进行连接到redis服务器
- return self._conn #如果已经有了_conn这个参数,说明已经连接过了,就直接返回这个连接
- #连接到本地redis服务器的函数
- def getConnection(self):
- self._conn = redis.Redis(connection_pool = self.pool)
- #实例化redis客户端类对象
- rcli = RedisClient()
- #rcli.conn返回的是一个连接
- #hex_get,
- res = rcli.conn.hget("record",name)
- #如果查询到结果就返回结果,没有的话就返回一个None
- if res is None:
- print("未查询到结果")
- else:
- res_obj=eval(res) #把他变成一个ditc字典
- #print函数%s代表着字符串。%d就是整数
- print("姓名:%s,最近一次战绩时间%s,用了%d次\r\n"%(name,res_obj["time"],res_obj["count"]))
复制代码 |
|