Python编程常用技巧,你全知道么?(14)

print(f\"</{name>\")

with tag(\"h1\"):

print(\"This is Title.\")

上面的代码段使用contextmanager管理器装饰器实现了内容管理协议 。 进入with块时 , 执行标记函数的第一部分(在yield之前) , 然后执行该块 , 最后执行其余的标记函数 。

重载运算符号的技巧

考虑到有很多比较运算符:__lt__ __le__ __gt__ , 对于一个类实现所有比较运算符可能会很烦人 。 这时候可以使用functools.total_ordering:

from functools import total_ordering

@total_ordering

class Number:

def __init__(self value):

self.value = https://mparticle.uc.cn/api/value

def __lt__(self other):

推荐阅读