Python 对类值装饰器,实现值的获取、设置、删除单例对象
需求:tcp连接或http连接的获取,关闭,设置,通过装饰器,实现全局单例,任意可以修改连接对象并且保持单例对象
注意:代码来源于Kombu队列源码里面 kombu.utils.objects.py
#!/usr/bin/env python # -*- coding: utf-8 -*- class cached_property: def __init__(self, fget=None, fset=None, fdel=None, doc=None): self.__get = fget self.__set = fset self.__del = fdel self.__doc__ = doc or fget.__doc__ self.__name__ = fget.__name__ self.__module__ = fget.__module__ # obj:是实例化类的对象,例如示例 : ConnectionHttp() # value:设置新值的连接对象,例如示例 : Connection def __get__(self, obj, type=None): # 获取值的时候调用 if obj is None: return self try: return obj.__dict__[self.__name__] except KeyError: value = obj.__dict__[self.__name__] = self.__get(obj) return value def __set__(self, obj, value): # 给对象设置值的时候,调用 if obj is None: return self if self.__set is not None: value = self.__set(obj, value) obj.__dict__[self.__name__] = value def __delete__(self, obj, _sentinel=object()): # 删除对象的时候调用 if obj is None: return self value = obj.__dict__.pop(self.__name__, _sentinel) if self.__del is not None and value is not _sentinel: self.__del(obj, value) def setter(self, fset): return self.__class__(self.__get, fset, self.__del) def deleter(self, fdel): return self.__class__(self.__get, self.__set, fdel) class Connection(object): """ 这个是一个连接类 """ pass class ConnectionHttp(object): @cached_property def connection(self): return Connection() @connection.setter # Prepares stored value def connection(self, value): if value is None: raise TypeError('Connection must be a connection') return value @connection.deleter def connection(self, value): # Additional action to do at del(self.attr) if value is not None: print('Connection {0!r} deleted'.format(value)) if __name__ == '__main__': print('默认类的单例对象======================') conn = ConnectionHttp() print(conn.connection) print(conn.connection) print('修改类对象单例的连接===================') conn.connection = Connection() print(conn.connection) print(conn.connection) print('删除类对象单例的连接===================') del conn.connection print(conn.connection)
# 运行结果
默认类的单例对象======================
<__main__.Connection object at 0x0000024615232FC8>
<__main__.Connection object at 0x0000024615232FC8>
修改类对象单例的连接===================
<__main__.Connection object at 0x00000246152323C8>
<__main__.Connection object at 0x00000246152323C8>
删除类对象单例的连接===================
Connection <__main__.Connection object at 0x00000246152323C8> deleted
<__main__.Connection object at 0x0000024615232FC8>
Process finished with exit code 0