2010-02-06 56 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]