本文介绍了如何跳过或忽略python装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个由装饰器包装的函数,该函数以HTML形式返回该函数的输出。我想在不使用装饰器进行HTML包装的情况下调用该函数。

There's a function that is wrapped by a decorator that returns the output of the function as HTML. I'd like to call that function without the HTML-wrapping of the decorator. Is that even possible?

示例:

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.


推荐答案

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



因为python中的函数和方法是对象,并且由于装饰器返回可调用对象,因此您可以在装饰方法上设置指向原始方法的属性,但是像my_object_instance.decorated_method.original_method()之类的调用会比较丑陋且不明确。

Since in python functions and methods are objects, and since a decorator returns a callable, you could set an attribute on the decorated method pointing to original method, but a call like my_object_instance.decorated_method.original_method() would be uglier and less explicit.

>>> 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!

这篇关于如何跳过或忽略python装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 13:17