gpt4 book ai didi

python - 如何使用另一个方法的签名创建一个新方法

转载 作者:行者123 更新时间:2023-12-03 00:04:43 25 4
gpt4 key购买 nike

如何从一个类复制方法的签名,并在另一个类中创建具有相同签名的“代理方法”?

我正在用 python 编写一个 RPC 库。服务器支持对服务器端类(C)的远程调用。当客户端连接到服务器时,它应该为C创建一个具有相同签名的代理类。当程序调用代理实例时,它应该在服务器上调用具有相同参数的函数。

最佳答案

考虑使用boltons.wraps - 这是文档的摘录:

boltons.funcutils.wraps(func, injected=None, **kw)

Modeled after the built-in functools.wraps(), this function is used to make your decorator’s wrapper functions reflect the wrapped function’s:

Name Documentation Module Signature

The built-in functools.wraps() copies the first three, but does not copy the signature. This version of wraps can copy the inner function’s signature exactly, allowing seamless usage and introspection. Usage is identical to the built-in version:

>>> from boltons.funcutils import wraps
>>>
>>> def print_return(func):
... @wraps(func)
... def wrapper(*args, **kwargs):
... ret = func(*args, **kwargs)
... print(ret)
... return ret
... return wrapper
...
>>> @print_return
... def example():
... '''docstring'''
... return 'example return value'
>>>
>>> val = example()
example return value
>>> example.__name__
'example'
>>> example.__doc__
'docstring'

In addition, the boltons version of wraps supports modifying the outer signature based on the inner signature. By passing a list of injected argument names, those arguments will be removed from the outer wrapper’s signature, allowing your decorator to provide arguments that aren’t passed in.

Parameters: func (function) – The callable whose attributes are to be copied.

injected (list) – An optional list of argument names which should not appear in the new wrapper’s signature.

update_dict (bool) – Whether to copy other, non-standard attributes of func over to the wrapper. Defaults to True.

inject_to_varkw (bool) – Ignore missing arguments when a **kwargs-type catch-all is present. Defaults to True.

For more in-depth wrapping of functions, see the FunctionBuilder type, on which wraps was built.

关于python - 如何使用另一个方法的签名创建一个新方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25460032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com