装潢师和课堂 [英] Decorators and in class

查看:45
本文介绍了装潢师和课堂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在嵌套良好的类结构中编写装饰器?例如,这可以在没有类的情况下正常工作:

Is there any way to write decorators within a class structure that nest well? For example, this works fine without classes:

def wrap1(func):
    def loc(*args,**kwargs):
        print 1
        return func(*args,**kwargs)
    return loc

def wrap2(func):
    def loc(*args,**kwargs):
        print 2
        return func(*args,**kwargs)
    return loc


def wrap3(func):
    def loc(*args,**kwargs):
        print 3
        return func(*args,**kwargs)
    return loc

def merger(func):
    return wrap1(wrap2(wrap3(func)))


@merger
def merged():
    print "merged"


@wrap1
@wrap2
@wrap3
def individually_wrapped():
    print "individually wrapped"

merged()
individually_wrapped()

输出为:

1
2
3
merged
1
2
3
individually wrapped

我想要的是。但是,现在让我们说,我想将合并 individually_wrapped 作为静态或类方法。只要将修饰符放在类名称空间之外,这也将起作用。有什么好的方法可以将装饰器放在命名空间中?我宁愿不列举所有无法使用的方法,但主要问题是,如果 merger 是一种方法,它将无法访问 wrapX 方法。也许这是一件愚蠢的事情,但是有人在同一个类中使用了所有装饰器和装饰器方法时,会得到类似的东西吗?

which is what I want. But now let's say that I want to make merged and individually_wrapped as static or class methods. This will also work, so long as the decorators are kept out of the class namespace. Is there any good way to put the decorators within the namespace? I'd rather not enumerate all the ways that won't work, but the main problem is that if merger is a method, it can't access the wrapX methods. Maybe this is a stupid thing to want to do, but has anyone gotten something like this to work, with all the decorators and decorated methods in the same class?

推荐答案

是否有任何好的方法可以将装饰器放入命名空间中?

"Is there any good way to put the decorators within the namespace?"

没有令人信服的理由。您有模块文件。这些是一个班级和一些装饰者的整洁容器。

There's no compelling reason for this. You have module files. Those are a tidy container for a class and some decorators.

您不需要装饰器作为类的方法-您可以从另一个方法中调用一个方法。

You don't ever need decorators as methods of the class -- you can just call one method from another.

这篇关于装潢师和课堂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆