2015-12-12 189 views
0

我寫一個裝飾類方法Python類方法裝飾

def decor(method): 
    def wrapped(self, *args, **kwargs): 
     return method(self, *args, **kwargs) 
    # [*] 
    return wrapped 

我想利用這個樣:

class A(metaclass=mymetaclass): 
    @decor 
    def meth(self): 
     pass 

我怎能方法/變量裝飾添加到已裝修方法類?我需要它在[*]附近做。 裏面裹着我可以寫self.__class__,但在這裏做什麼?

+0

你可以用'method.im_class' http://stackoverflow.com/questions/7680446/get-python-functions-owning-class-from-decorator –

回答

3

我無法想象的方式來滿足這樣的要求,因爲decor函數只接收一個函數對象一無所知含有類。

,我可以想像,唯一的解決方法是使用參數化的裝飾,並通過它的類被裝飾

def decor(cls): 
    def wrapper(method): 
     def wrapped(self, *args, **kwargs): 
      return self.method(*args, **kwargs) 
     print method # only a function object here 
     return wrapped 
    print cls # here we get the class and can manipulate it 
    return wrapper 

class A 
    @decor(A) 
    def method(self): 
     pass 

或者,你可以裝飾類本身:

def cdecor(cls): 
    print 'Decorating', cls # here we get the class and can manipulate it 
    return cls 

@cdecor 
class B: 
    def meth(self): 
     pass 

給出:

Decorating __main__.B 
0

它看起來是不能直接,根據該水庫ponse:

Get Python function's owning class from decorator

你可以做什麼,而不是正在爲你的類的裝飾,這樣的事情:

class InsertMethod(object): 
    def __init__(self, methodToInsert): 
     self.methodToInsert = methodToInsert 

    def __call__(self, classObject): 
     def wrapper(*args, **kwargs): 
      setattr(classObject, self.methodToInsert.__name__, self.methodToInsert) 
      return classObject(*args, **kwargs) 
     return wrapper 

def IWillBeInserted(self): 
    print "Success" 


@InsertMethod(IWillBeInserted) 
class Something(object): 
    def __init__(self): 
     pass 

    def action(self): 
     self.IWillBeInserted() 


a = Something() 
a.action() 
0

其實,你可以裝飾類本身:

def class_decorator(class_): 
    class_.attribute = 'value' 
    class_.method = decorate(class_.method) 
    return class_ 

@class_decorator 
class MyClass: 
    def method(self): 
     pass