Python类方法d

2024-06-16 09:26:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我为类方法编写了一个装饰器

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

我想用这种方式:

^{pr2}$

如何在decorator中将方法/变量添加到具有修饰方法的类中?我需要它靠近[*]。 在包装内我可以写self.__class__,但在这里该怎么办?在


Tags: 方法selfreturndef方式args装饰decorator
3条回答

根据这一回应,这似乎是不可能的:

Get Python function's owning class from decorator

相反,您可以为您的类提供一个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()

我无法想象满足这种要求的方法,因为decor函数只接收一个对包含类一无所知的函数对象。在

我能想到的唯一解决方法是使用参数化decorator并将被修饰的类传递给它

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

或者,可以装饰类本身:

^{pr2}$

给出:

Decorating __main__.B

实际上,您可以装饰类本身:

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

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

相关问题 更多 >