python - 访问 Python 类的函数子集

标签 python xml-rpc

使用具有 xmlrpc 代理作为其对象属性之一的类

def __init__(self):
    self.proxy = ServerProxy(...)
    # ...

我正在尝试简化代理的某些功能的使用。应该只使用代理函数的一个子集,因此我想到为它们创建一组微型包装函数,例如

def sample(self):
    """ A nice docstring for a wrapper function. """
    self.proxy.sample()

是否有一种获取所有包装函数列表的好方法?我正在考虑类似 dir() 的方法,但随后我需要过滤对象的包装函数。 xmlrpc 自省(introspection) ( http://xmlrpc-c.sourceforge.net/introspection.html ) 也无济于事,因为我不想使用/提供服务器的所有功能。

也许在包装器上设置一个属性以及 @staticmethod get_wrappers() 可以达到目的。具有 _wrapper 后缀不适合我的用例。跟踪可用的类中的静态列表太容易出错。所以我正在寻找关于如何最好地获取包装函数列表的好主意?

最佳答案

我不是 100% 确定这是否是您想要的,但它确实有效:

def proxy_wrapper(name, docstring):
    def wrapper(self, *args, **kwargs):
        return self.proxy.__getattribute__(name)(*args, **kwargs)
    wrapper.__doc__ = docstring
    wrapper._is_wrapper = True
    return wrapper

class Something(object):
    def __init__(self):
        self.proxy = {}

    @classmethod
    def get_proxy_wrappers(cls):
        return [m for m in dir(cls) if hasattr(getattr(cls, m), "_is_wrapper")]

    update = proxy_wrapper("update", "wraps the proxy's update() method")
    proxy_keys = proxy_wrapper("keys", "wraps the proxy's keys() method")    

然后

>>> a = Something()
>>> print a.proxy
{}
>>> a.update({1: 42})
>>> print a.proxy
{1: 42}
>>> a.update({"foo": "bar"})
>>> print a.proxy_keys()
[1, 'foo']
>>> print a.get_proxy_wrappers()
['proxy_keys', 'update']

关于python - 访问 Python 类的函数子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2213289/

相关文章:

python - Tkinter:框架(?)四处移动

没有循环导入的 Python 类型提示

python - Numpy:在一台机器上耗尽内存,而在另一台机器上完成相同的任务

python - 在 Matplotlib 3 中设置具有共享轴的物理方形子图

php - 大 POST 数据被剪切(XMLRPC 调用)

python - 如何获取所有帖子的ID?

python - Confluence XML-RPC : Set the "creation" date

python - 根据值删除 Pandas 中的 DataFrame 列

python - Qt (PyQt) 事件循环内的 xmlrpc?

c++ - 服务器端库 (c/c++) xmlrpc