Python零碎小知识

栏目: Python · 发布时间: 6年前

内容简介:今天读Mock的源代码,发现的几个新玩意儿。以后读代码发现了也记这里吧 :smile:原理很简单,只是觉得很有趣啦,哈哈。:smile:哈哈哈,是不是也很简单。不过这只能算是一个trick,不能满足更灵活的要求,例如 要格式化更长的字符串咋办。

今天读Mock的源代码,发现的几个新玩意儿。以后读代码发现了也记这里吧 :smile:

  • dict有个 setdefault 方法, dict.setdefault(key, default) 相当于 dict.get(key, default) 并且如果 dict[key] 为空还会 dict.set(key, default)
In [1]: a = dict()

In [2]: a.setdefault("A", 1)
Out[2]: 1

In [3]: a.setdefault("A", 2)
Out[3]: 1
  • 判断一个方法是否为 magic 方法的小trick:
def _is_magic(name):
    return '__%s__' % name[2:-2] == name
In [1]: def _is_magic(name):
   ...:     return '__%s__' % name[2:-2] == name
   ...:

In [2]: _is_magic("__magic__")
Out[2]: True

In [3]: _is_magic("name")
Out[3]: False

原理很简单,只是觉得很有趣啦,哈哈。:smile:

  • lazy形式格式化字符串。平时我们格式化字符串都是 '%s %s' % ('hello', 'world') 这样子。但是如果有需求说要先填充一个,然后后边再填充呢?当然我们可以先格式化 一部分,然后后面再append新的字符串。但是也可以这样:
>>> '%s %%s' % 'hello'
'hello %s'
>>> '%s %%s' % 'hello' % 'world'
'hello world'
>>>

哈哈哈,是不是也很简单。不过这只能算是一个trick,不能满足更灵活的要求,例如 要格式化更长的字符串咋办。

  • 比较两个数大小。这个是从unittest的utils里看到的,感觉还是蛮优雅的,利用了 Python中布尔值也可以做数值运算的特性:
In [1]: def cmp(x, y):
   ...:     return (x > y) - (x < y)
   ...:

In [2]: cmp(1, 2)
Out[2]: -1

In [3]: cmp(2, 1)
Out[3]: 1

In [4]: cmp(2, 2)
Out[4]: 0

In [5]:

因为C89没有定义布尔类型,0就是false,1就是true。所以c也可以这样搞。

$ cat ~/tests/test.c
#include <stdio.h>

int cmp(int x, int y) {
    return (x > y) - (x < y);
}

int main(void) {
    int a = 1;
    int b = 2;
    printf("cmp(%d, %d) = %d\n", a, b, cmp(a, b));
}
$ ~/tests/a.out
cmp(1, 2) = -1

贴这个出来,主要是平时写惯了 if...else... 固化了思维,突然看到这个有点 眼前一亮的感觉。。。

import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print file

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Web Security Testing Cookbook

Web Security Testing Cookbook

Paco Hope、Ben Walther / O'Reilly Media / 2008-10-24 / USD 39.99

Among the tests you perform on web applications, security testing is perhaps the most important, yet it's often the most neglected. The recipes in the Web Security Testing Cookbook demonstrate how dev......一起来看看 《Web Security Testing Cookbook》 这本书的介绍吧!

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具