python decorator. decorator_Python decorators和decorator模式有什么区别?

“Python decorators”和“decorator模式”有什么区别?

什么时候应该使用Python decorators,什么时候应该使用decorator模式?

我正在寻找Python decorators和decorator模式的示例。

@AcceptedAnswer

我知道Jakob Bowyer's answer是有效的。但正是斯里卡尔的回答让我明白了原因。

在Srikar给出答案并研究了给定的资源之后,我编写了这个示例,以便能够可视化并理解Python装饰器和装饰器模式。

我必须不同意Srikar的“Python decorator s不是decorator模式的实现”。据我所知,我坚信Python decorators是decorator模式的一个实现。只是不是以经典的方式。

此外,我还需要补充一点,尽管Srikar说“Python decorators在定义时为函数和方法添加功能,您可以在运行时轻松使用Python decorators”。

然而,我仍然将Srikar的答案标记为已接受,因为它帮助我理解Python中装饰器模式的the implementation。"""

Testing Python decorators against the decorator pattern

"""

def function(string):

return string

def decorator(wrapped):

def wrap(string):

# Assume that this is something useful

return wrapped(string.upper())

return wrap

def method_decorator(wrapped):

def wrap(instance, string):

# Assume that this is something useful

return wrapped(instance, string.upper())

return wrap

@decorator

def decorated_function(string):

print('! '.join(string.split(' ')))

class Class(object):

def __init__(self):

pass

def something_useful(self, string):

return string

class Decorator(object):

def __init__(self, wrapped):

self.wrapped = wrapped

def something_useful(self, string):

string = '! '.join(string.split(' '))

return self.wrapped().something_useful(string)

@method_decorator

def decorated_and_useful(self,string):

return self.something_useful(string)

if __name__ == '__main__':

string = 'Lorem ipsum dolor sit amet.'

print(function(string)) # Plain function

print(decorator(function)(string)) # Python decorator at run time

print(decorated_function(string)) # Python decorator at definition time

a = Class()

print(a.something_useful(string)) # Plain method

b = Decorator(Class)

print(b.something_useful(string)) # Decorator pattern

print(b.decorated_and_useful(string)) # Python decorator decorated the decorator pattern

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值