2017-02-25 39 views
0

我想在屬性獲取或/和設置之前或之後進行一些操作。 這段代碼中棘手的部分是我無法修改原始類。包裝獲取和設置屬性方法,而無需編輯原始類

該類的方法沒有問題,它按預期工作。但我找不到處理財產的方法。我有一個錯誤:

TypeError: readonly attribute 

如果有人可以幫助我找到正確的方向...

這是I類不能修改:

class Test(object): 
    def __init__(self): 
     super(Test, self).__init__() 
     self._param = None 
     self._controler = None 
     self._message = None 
    @property 
    def param(self): 
     return self._param 
    @param.setter 
    def param(self, param): 
     self._param = param 

    @property 
    def controler(self): 
     return self._controler 

    def message(self): 
     print('message') 

這是我寫的,使包裝工作,這將是我的模塊的一部分

def add_things_before_and_after(function_to_enhance): 
    def new_wrapper(self): 
     print("Before function execution") 
     function_to_enhance(self) 
     print("After function execution") 
    return new_wrapper 

這是編寫使用包裝和insta的代碼nciate類

# this one works as expected 
Test.message = add_things_before_and_after(Test.message) 
# these two lines does not work 
Test.param.fget = add_things_before_and_after(Test.param.fget) 
Test.controler.fget = add_things_before_and_after(Test.controler.fget) 

test = Test() 
test.message() 
test.param = 1 
print(test.param) 
print(test.controler) 

回答

1

這可能是由一個新覆蓋整個param物業辦。但是,您的修飾器函數必須修復以返回包裝函數的值。

functools.wraps的是保持被包裝的函數的屬性(名稱,文檔等)的好方法。

from functools import wraps 

def add_things_before_and_after(function_to_enhance): 
    @wraps(function_to_enhance) 
    def new_wrapper(self): 
     print("Before function execution") 
     r = function_to_enhance(self) 
     print("After function execution") 
     return r 
    return new_wrapper 

# this one works as expected 
Test.message = add_things_before_and_after(Test.message) 

# these two lines should work 
Test.param = property(add_things_before_and_after(Test.param.fget), Test.param.fset) 
Test.controler = property(add_things_before_and_after(Test.controler.fget), Test.controler.fset) 

test = Test() 
test.message() 
test.param = 1 
print(test.param) 
print(test.controler) 

# ==Output== 
# 
# Before function execution 
# message 
# After function execution 
# Before function execution 
# After function execution 
# 1 
# Before function execution 
# After function execution 
# None 
+0

非常感謝你@kofrasa –

+0

不客氣@ reno-。快樂的編碼! – kofrasa