2010-02-06 162 views
3

功能的子集,使用具有一个XML-RPC的代理,因为它的对象的属性访问的Python类

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后缀不适合我的用例。跟踪可用的类中的静态列表太容易出错。所以我正在寻找关于如何最好地获取包装函数列表的好主意?

回答

3

我不是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'] 
+0

谢谢,这看起来恰到好处。我会在星期一试试:) – 2010-02-06 20:43:36

2

使用XML-RPC自省来获取服务器列表和交叉处,与你的对象的属性。例如:

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