Подтвердить что ты не робот

Как пропустить или игнорировать декораторы python

Здесь есть функция, которая обертывается декоратором, который возвращает результат функции как HTML. Я бы назвал эту функцию без HTML-обертывания декоратора. Возможно ли это?

Пример:

class a:
    @HTMLwrapper
    def returnStuff(input):
        return awesome_dict

    def callStuff():
        # here I want to call returnStuff without the @HTMLwrapper, 
        # i just want the awesome dict.
4b9b3361

Ответ 1

class a:
    @HTMLwrapper
    def return_stuff_as_html(self, input):
        return self.return_stuff(input)
    def return_stuff(self, input):
        return awesome_dict

Я делал то же самое, ожидая ответа, и он отлично подходит для меня, но мне все равно хотелось бы узнать, есть ли еще лучший способ:) - olofom

Так как в функциях и методах python есть объекты, и поскольку декоратор возвращает вызываемый, вы можете установить атрибут в декорированном методе, указывающем на оригинальный метод, но вызов типа my_object_instance.decorated_method.original_method() будет более уродливым и менее явный.

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let do more of those!

Ответ 2

__author__ = 'Jakob'

class OptionalDecoratorDecorator(object):
    def __init__(self, decorator):
        self.deco = decorator

    def __call__(self, func):
        self.deco = self.deco(func)
        self.func = func
        def wrapped(*args, **kwargs):
            if kwargs.get("no_deco") is True:
                return self.func()
            else:
                return self.deco()
        return wrapped

def spammer(func):
    def wrapped():
        print "spam"
        return func()
    return wrapped

@OptionalDecoratorDecorator(spammer)
def test():
    print "foo"

test()
print "***"
test(no_deco=True)

Ответ 3

Конечно:

class Example(object):
    def _implementation(self):
        return something_awesome()

    returnStuff = HTMLwrapper(_implementation)

    def callStuff(self):
        do_something_with(self._implementation())