zoukankan      html  css  js  c++  java
  • 灵活的左移位( << )操作

    深入的学习了下 git 的各种用法。 闲来无事 看看django的提交历史。 想看看各位牛人都提交了些什么。
    24小时前django的master分支更新的一段代码。 很有意思。


    | +++ b/django/template/defaultfilters.py
    | @@ -827,17 +827,23 @@ def filesizeformat(bytes):
    |

    | filesize_number_format = lambda value: formats.number_format(round(value, 1), 1)
    |

    | - if bytes < 1024:
    | + KB = 1<<10
    | + MB = 1<<20
    | + GB = 1<<30
    | + TB = 1<<40
    | + PB = 1<<50
    | +
    | + if bytes < KB:
    | return ungettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes}
    | - if bytes < 1024 * 1024:
    | - return ugettext("%s KB") % filesize_number_format(bytes / 1024)
    | - if bytes < 1024 * 1024 * 1024:
    | - return ugettext("%s MB") % filesize_number_format(bytes / (1024 * 1024))
    | - if bytes < 1024 * 1024 * 1024 * 1024:
    | - return ugettext("%s GB") % filesize_number_format(bytes / (1024 * 1024 * 1024))
    | - if bytes < 1024 * 1024 * 1024 * 1024 * 1024:
    | - return ugettext("%s TB") % filesize_number_format(bytes / (1024 * 1024 * 1024 * 1024))
    | - return ugettext("%s PB") % filesize_number_format(bytes / (1024 * 1024 * 1024 * 1024 * 1024))
    | + if bytes < MB:
    | + return ugettext("%s KB") % filesize_number_format(bytes / KB)
    | + if bytes < GB:
    | + return ugettext("%s MB") % filesize_number_format(bytes / MB)
    | + if bytes < TB:
    | + return ugettext("%s GB") % filesize_number_format(bytes / GB)
    | + if bytes < PB:
    | + return ugettext("%s TB") % filesize_number_format(bytes / TB)
    | + return ugettext("%s PB") % filesize_number_format(bytes / PB)
    |

    | @register.filter(is_safe=False)
    | def pluralize(value, arg='s'):

    这里使用了 左移位操作 定义了各种文件大小单位的变量。这么操作我想应该比原本的直接乘效率要高的多吧。

    为什么不直接写到 if 语句中 而是要单独列出来呢?

    其实想想 理由很简单。 这样做才足够 pythonic 。明确的告诉读到这段代码的人。他的意图是什么。

    python 就是这么的直白。 I love python!

  • 相关阅读:
    http 请求头设置缓存
    手把手教你开发chrome扩展一:开发Chrome Extenstion其实很简单
    django如何用邮箱代替用户名登录
    python函数式编程学习之map,reduce,filter,sorted
    python traceback学习(转)
    python logging模块学习(转)
    python pip安装lxml失败(转)
    python下性能提示
    python移植性提示
    python测试与调试提示
  • 原文地址:https://www.cnblogs.com/pylemon/p/2599934.html
Copyright © 2011-2022 走看看