选自medium,作者:Martin Heinz,机器之心编译,参与:王子嘉、熊宇轩。
介绍 Python 炫酷功能(例如,变量解包,偏函数,枚举可迭代对象等)的文章层出不穷。但是还有很多 Python 的编程小技巧鲜被提及。因此,本文会试着介绍一些其它文章没有提到的小技巧,这些小技巧也是我平时会用到的的。让我们一探究竟吧!

整理用户输入的问题在编程过程中极为常见。通常情况下,将字符转换为小写或大写就够了,有时你可以使用正则表达式模块「Regex」完成这项工作。但是如果问题很复杂,可能有更好的方法来解决:
user_input = "This\nstring has\tsome whitespaces...\r\n"character_map = { ord('\n') : ' ', ord('\t') : ' ', ord('\r') : None}user_input.translate(character_map) # This string has some whitespaces... 在本例中,你可以看到空格符「\ n」和「\ t」都被替换成了单个空格,「\ r」都被删掉了。这只是个很简单的例子,我们可以更进一步,使用「unicodedata」程序包生成大型重映射表,并使用其中的「combining()」进行生成和映射,我们可以
迭代器切片(Slice)
import itertoolss = itertools.islice(range(50), 10, 20) # <itertools.islice object at 0x7f70fab88138>for val in s: ...跳过可迭代对象的开头
string_from_file = """// Author: ...// License: ...//// Date: ...Actual content..."""import itertoolsfor line in itertools.dropwhile(lambda line: line.startswith("//"), string_from_file.split("\n")): print(line)只包含关键字参数的函数 (kwargs)
def test(*, a, b): passtest("value for a", "value for b") # TypeError: test() takes 0 positional arguments...test(a="value", b="value 2") # Works...创建支持「with」语句的对象
class Connection: def __init__(self): ... def __enter__(self): # Initialize connection... def __exit__(self, type, value, traceback): # Close connection...with Connection() as c: # __enter__() executes ... # conn.__exit__() executesfrom contextlib import contextmanager@contextmanagerdef tag(name): print(f"<{name}>") yield print(f"</{name}>")with tag("h1"): print("This is Title.")用「__slots__」节省内存
如果你曾经编写过一个创建了某种类的大量实例的程序,那么你可能已经注意到,你的程序突然需要大量的内存。那是因为 Python 使用字典来表示类实例的属性,这使其速度很快,但内存使用效率却不是很高。通常情况下,这并不是一个严重的问题。但是,如果你的程序因此受到严重的影响,不妨试一下「__slots__」:
class Person: __slots__ = ["first_name", "last_name", "phone"] def __init__(self, first_name, last_name, phone): self.first_name = first_name self.last_name = last_name self.phone = phone当我们定义了「__slots__」属性时,Python 没有使用字典来表示属性,而是使用小的固定大小的数组,这大大减少了每个实例所需的内存。使用「__slots__」也有一些缺点:我们不能声明任何新的属性,我们只能使用「__slots__」上现有的属性。而且,带有「__slots__」的类不能使用多重继承。
限制「CPU」和内存使用量
如果不是想优化程序对内存或 CPU 的使用率,而是想直接将其限制为某个确定的数字,Python 也有一个对应的库可以做到:
import signalimport resourceimport os# To Limit CPU timedef time_exceeded(signo, frame): print("CPU exceeded...") raise SystemExit(1)def set_max_runtime(seconds): # Install the signal handler and set a resource limit soft, hard = resource.getrlimit(resource.RLIMIT_CPU) resource.setrlimit(resource.RLIMIT_CPU, (seconds, hard)) signal.signal(signal.SIGXCPU, time_exceeded)# To limit memory usagedef set_max_memory(size): soft, hard = resource.getrlimit(resource.RLIMIT_AS) resource.setrlimit(resource.RLIMIT_AS, (size, hard))控制可以/不可以导入什么
def foo(): passdef bar(): pass__all__ = ["bar"]实现比较运算符的简单方法
from functools import total_ordering@total_orderingclass Number: def __init__(self, value): self.value = value def __lt__(self, other): return self.value < other.value def __eq__(self, other): return self.value == other.valueprint(Number(20) > Number(3))print(Number(1) < Number(5))print(Number(15) >= Number(15))print(Number(10) <= Number(2))结语