访问Python类的某个子集功能

2024-06-01 10:08:24 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我正在尝试简化代理的一些功能的使用。只使用代理函数的一个子集,因此我考虑为它们创建一组小包装函数,比如

^{pr2}$

有没有一个好方法可以得到所有包装器函数的列表?我正在考虑类似dir()的东西,但是接下来我需要过滤对象的包装函数。xmlrpc自省(http://xmlrpc-c.sourceforge.net/introspection.html)也没有什么帮助,因为我不想使用/提供服务器的所有功能。在

也许在wrappers上设置一个属性和一个@staticmethod get_wrappers()可以做到这一点。有一个_包装器后缀不适合我的用例。类中跟踪可用对象的静态列表太容易出错。所以我在寻找如何最好地获得包装器函数列表的好主意?在


Tags: 对象函数self功能代理列表属性init
2条回答

我不能百分之百确定这是否是你想要的,但它是有效的:

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")    

那么

^{pr2}$

使用xml-rpc自省来获取服务器列表并将其与对象的属性相交。比如:

loc = dir(self)
rem = proxy.listMethods() # However introspection gets a method list
wrapped = [x for x in rem if x in loc]

相关问题 更多 >