定义

  1. class Singleton(object):
  2. """Singleton base class"""
  3. _instance_lock = _thread.allocate_lock()
  4. def __init__(self, *args, **kwargs):
  5. pass
  6. def __new__(cls, *args, **kwargs):
  7. if not hasattr(cls, "instance_dict"):
  8. Singleton.instance_dict = {}
  9. if str(cls) not in Singleton.instance_dict.keys():
  10. with Singleton._instance_lock:
  11. _instance = super().__new__(cls)
  12. Singleton.instance_dict[str(cls)] = _instance
  13. return Singleton.instance_dict[str(cls)]

使用

  1. class SystemRuning(Singleton):
  2. def __init__(self):
  3. pass
  4. def GetRunStatus(self):
  5. usr = uos.statvfs("/usr")
  6. memA = gc.mem_alloc()/1024
  7. memF = gc.mem_free()/1024
  8. bak = uos.statvfs("/bak")
  9. p1=(1-(usr[0] * usr[3])/(usr[0] * usr[2]))*100.00
  10. p2=(memA/(memF+memA))*100.00
  11. return "====SystemRun====\r\n==usr:\r\n 文件块数:{}\r\n 文件空间:{}\r\n 可用块数: {}\r\n 可用空间:{} KB\r\n 已使用率:{}%\r\n==bar:\r\n 文件块数:{}\r\n 文件空间:{}\r\n 可用块数: {}\r\n 可用空间:{} KB\r\n===RAM:\r\n 已经使用:{}KB\r\n 剩余可用:{}KB\r\n 已使用率:{}%".format(usr[2],(usr[0] * usr[2])/1024,usr[3],(usr[0]*usr[3])/1024,'%.2f'%p1,bak[0],(bak[0] * bak[2])/1024,bak[3],(bak[0] * bak[3])/1024,'%.2f'%memA,'%.2f'%memF,'%.2f'%p2)

调用

  1. print(SystemRuning())
  2. print(SystemRuning())
  • 打印出来为同一对象
  • 都会执行 __init__ 方法