装饰器类和装饰器函数之间的区别 [英] Difference between decorator classes and decorator functions

查看:317
本文介绍了装饰器类和装饰器函数之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这就是它们的称呼方式,但我会举一些例子,以防万一。

I guess that's how they are called, but I will give examples just in case.

装饰类:

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

    def __call__(self, *args, **kwargs):
        print 'something'
        self.func(*args, **kwargs)

装饰函数:

def decorator(func):
    def wrapper(*args, **kwargs):
        print 'something'
        return func(*args, **kwargs)
    return wrapper

使用一个或另一个仅仅是一种口味吗?有什么实际的区别吗?

Is using one or the other just a matter of taste? Is there any practical difference?

推荐答案

如果您可以编写函数来实现装饰器,则应该使用它。但是并非所有装饰器都可以轻松地编写为一个函数-例如,当您要存储某些内部状态时。

If you can write a function to implement your decorator you should prefer it. But not all decorators can easily be written as a function - for example when you want to store some internal state.

class counted(object):
    """ counts how often a function is called """
    def __init__(self, func):
        self.func = func
        self.counter = 0

    def __call__(self, *args, **kwargs):
        self.counter += 1
        return self.func(*args, **kwargs)


@counted
def something():
    pass

something()
print something.counter

我见过人们(包括我自己)经过荒唐的努力,只用函数编写装饰器。我仍然不知道为什么,一个类的开销通常可以忽略不计。

I've seen people (including myself) go through ridiculous efforts to write decorators only with functions. I still have no idea why, the overhead of a class is usually totally negligible.

这篇关于装饰器类和装饰器函数之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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