Python字节单位转换实例

yipeiwu_com6年前Python基础

我就废话不多说了,直接上代码!

from enum import Enum
 
class Values():
  values={'B':1}
  @staticmethod
  def getValues():
    if len(Values.values)<=1:
      kbunits=['KB','MB','GB','TB','PB','EB','ZB','YB','BB','NB','DB']
      kibunits=['KiBi','MiB','GiB','TiB','PiB','EiB','ZiB','YiB','BiB','NiB','DiB']
      for index,unit in enumerate(kibunits):
        Values.values[unit]=1<<(index+1)*10
      for index,unit in enumerate(kbunits):
        Values.values[unit]=10**((index+1)*3)
    return Values.values
  @staticmethod
  def get(key):
    return Values.getValues().get(key)
  
class Units(Enum):
 
  def __new__(cls,name):
    obj = object.__new__(cls)
    print (name)
    obj._value_=Values.get(name)
    return obj
  B=('B')
  KB=('KB')
  KiB=('KiBi')
  MB=('MB')
  MiB=('MiB')
  GB=('GB')
  GiB=('GiB')
  TB=('TB')
  TiB=('TiB')
  PB=('PB')
  PiB=('PiB')
  EB=('EB')
  EiB=('EiB')
  ZB=('ZB')
  ZiB=('ZiB')
  YB=('YB')
  YiB=('YiB')
  BB=('BB')
  BiB=('BiB')
  NB=('NB')
  NiB=('NiB')
  DB=('DB')
  DiB=('DiB')
 
class ByteUnitConversionUtil():
  __defaultformat="%.5f"
  @staticmethod
  def convert(value,unit=Units.B,format=__defaultformat):
    if(unit==Units.B):
      return str(value).split(".",2)[0]+unit.name
    else:
      return (format % (value/unit.value))+unit.name
    
if __name__=="__main__":
  print(ByteUnitConversionUtil.convert(12313213453,Units.KiB,"%.2f"))

以上这篇Python字节单位转换实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

浅谈Python的垃圾回收机制

一.垃圾回收机制 Python中的垃圾回收是以引用计数为主,分代收集为辅。引用计数的缺陷是循环引用的问题。 在Python中,如果一个对象的引用数为0,Python虚拟机就会回收这个对象...

简单了解什么是神经网络

简单了解什么是神经网络

深度学习这个词指的是训练神经网络。深代表着非常大的神经网络。那么神经网络到底是什么呢?看了这篇文章后你就会有很直观的认识了。 我们从一个房价预测的例子开始吧。因为现在房价太他妈...

python采集百度百科的方法

本文实例讲述了python采集百度百科的方法。分享给大家供大家参考。具体如下: #!/usr/bin/python # -*- coding: utf-8 -*- #encoding...

Python编程中装饰器的使用示例解析

装饰函数和方法 我们先定义两个简单的数学函数,一个用来计算平方和,一个用来计算平方差: # get square sum def square_sum(a, b): return...

python调用c++返回带成员指针的类指针实例

这个是OK的: class Rtmp_tool { public: int m_width; AVCodecContext * c; }; 指针的用法如下: Rtm...