• 灵活的左移位( << )操作


    深入的学习了下 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!

  • 相关阅读:
    颜色空间RGB与HSV(HSL)的转换
    表示数值的字符串
    正则表达式匹配
    构建乘积数组
    Linux以百万兆字节显示内存大小
    OCP-1Z0-051-题目解析-第26题
    2014华为机试(一)
    android Manifest.xml选项
    TXT小说朗读正式版
    Codeforces Round #256 (Div. 2) B. Suffix Structures
  • 原文地址:https://www.cnblogs.com/pylemon/p/2599934.html
Copyright © 2020-2023  润新知