2012-03-14 114 views
10

有一个由装饰器包装的函数,该装饰器将函数的输出作为HTML返回。我想在没有装饰器的HTML包装的情况下调用该函数。这甚至有可能吗?如何跳过或忽略python装饰器

例子:

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. 

回答

4
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函数和方法中是对象,并且由于装饰器返回可调用对象,所以可以在装饰方法上指定一个属性指向原始方法od,但是像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's a bad idea. 
If the implementation is easy to explain, it may be a good idea. 
Namespaces are one honking great idea -- let's do more of those! 
+0

我做了几乎同样的事情在等待,但我不允许原来的功能,所以我只是改名returnStuff改变returnStuffHelper和装饰returnStuff,然后调用而不是我的函数returnStuffHelper。其他代码需要returnStuff返回HTML。 – olofom 2012-03-14 12:53:05

+0

@olofom:已更新 – 2012-03-14 13:03:32

+0

我不允许更改装饰器或原始方法,所以我猜这对我来说不会更好。感谢:) – olofom 2012-03-14 14:29:37

0

肯定的:

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

    returnStuff = HTMLwrapper(_implementation) 

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

我不允许更改装饰功能,其他代码依赖于它。我用保罗斯卡丁的代码来代替。 – olofom 2012-03-14 12:57:25

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) 
+0

不错的例子,进入我的小片段库。 – ohmi 2012-03-14 15:36:40

+0

:D YAY我喜欢在这些模块中。 – 2012-03-14 15:41:10

+0

这太好了。非常有用的片段。 – krishnab 2015-12-09 06:51:49