python cookbook第三版学习笔记十九:未包装的函数添加参数

比如有下面如下的代码,每个函数都需要判断debug的是否为True,而默认的debugFalse

def a(x,debug=False):

    if debug:

        print('calling a')

 

def b(x,y,z,debug=False):

    if debug:

        print('calling b')

 

def c(x,y,debug=False):

    if debug:

        print('calling c')

上面的代码可以编写一个装饰器为被包装的函数添加额外的参数来简化,但是添加的参数不能影响到该函数已有的调用约定。定义如下的一个装饰器

 

def optional_debug(func):

    @wraps(func)

    def wrapper(*args,debug=False,**kwargs):

        if debug:

            print('Calling',func.__name__)

        return func(*args,**kwargs)

return wrapper

 

@optional_debug

def spam(a,b):

print(a,b)

 

spam(1,2)

>>>1,2

spam(1,2,debug=True)

>>>Calling spam

1,2

 

利用装饰器给类定义打补丁

我们想检查一部分类的定义,以此来修改类的行为,但是不想通过继承或者元类的方式来做

我们可以用一个类装饰器重写__getattribute__

def log_getattribute(cls):

    print(cls)

    orig_getattribute=cls.__getattribute__

    def new_getattribute(self,name):

        print('geting:',name)

        return orig_getattribute(self,name)

    cls.__getattribute__=new_getattribute

    return cls

 

@log_getattribute

class A:

    def __init__(self,x):

        self.x=x

    def spam(self):

        pass

 

(1) 首先通过orig_getattribute=cls.__getattribute__将初始的__getattribute__方法赋值给orig_getattribute,便于在new_getattribute调用

(2) 然后通过cls.__getattribute__=new_getattribute将类的__getattribute__赋值为new_getattribute,这样在类中调用__getattribute__的时候,其实是调用的new_getattribute

(3) 最后return cls

 

a=A(42)

print(a.x)

运行结果:

geting: x

42

 

@font-face { font-family: "Times New Roman"; }@font-face { font-family: "宋体"; }p.MsoNormal { margin: 0pt 0pt 0.0001pt; text-align: justify; font-family: "Times New Roman"; font-size: 10.5pt; }span.msoIns { text-decoration: underline; color: blue; }span.msoDel { text-decoration: line-through; color: red; }div.Section0 { }

posted @   red_leaf_412  阅读(226)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
历史上的今天:
2017-10-21 Learning Scrapy 中文版翻译 第一章
点击右上角即可分享
微信分享提示