小编Shi*_*Zhu的帖子

Python:使用装饰器修改函数的内部行为

我正在学习使用python装饰器.

def my_dcrtr(fun):
    def new_fun():
        return fun()
    return new_fun
Run Code Online (Sandbox Code Playgroud)

我意识到装饰功能'fun'就像装饰器里面的黑盒子一样.我可以选择在new_fun中使用fun()或者根本不使用fun().但是,我不知道我是否可以闯入'有趣'并与new_fun中的fun的本地范围进行交互?

例如,我正在尝试使用python制作玩具远程程序调用(RPC).

def return_locals_rpc_decorator(fun):
    def decorated_fun(*args, **kw):
        local_args = fun(*args, **kw)
        # pickle the local_args and send it to server
        # server unpickle and doing the RPC
        # fetch back server results and unpickle to results
        return rpc_results

    return decorated_fun


@return_locals_rpc_decorator
def rpc_fun(a, b, c=3):
    return locals() # This looks weird. how can I make this part of the decorator?


print(rpc_fun(2, 1, 6))
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我尝试使用'locals()'命令在运行时获取rpc_fun的参数列表.然后将其发送到服务器执行.而不是让rpc_fun返回其locals(),是否可以使用装饰器来检索修饰函数的参数空间?

python decorator

6
推荐指数
1
解决办法
214
查看次数

标签 统计

decorator ×1

python ×1