2015-12-12 27 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