-
Decorator
2020-06-11 22:08:45Decorator 是一种与类相关的语法,用来注释或修改类和类方法与属性,许多面向对象的语言存在,一般与类class相关,普通函数不要使用。 进入代码就会执行完成 装饰器是一种函数,写成@+函数名,可以放在类和类方法的... -
decorator
2019-02-10 14:47:33请编写一个decorator,能在函数调用的前后打印出'begin call'和'end call'的日志。 再思考一下能否写出一个@log的decorator,使它既支持: @log def f(): pass 又支持 @log('execute') def f(): pass def ...请编写一个decorator,能在函数调用的前后打印出'begin call'和'end call'的日志。 再思考一下能否写出一个@log的decorator,使它既支持: @log def f(): pass 又支持 @log('execute') def f(): pass
def metric(ar = None): def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): if ar != None: print('begin call %s %s'%(func.__name__, ar)) else: print('begin call %s'%func.__name__) f = func(*args, **kw) if ar != None: print('end call %s %s'%(func.__name__, ar)) else: print('end call %s'%func.__name__) return f return wrapper return decorator
调用:
-
Design Pattern - Decorator(C#)
2019-02-03 15:37:37This real-world code demonstrates the Decorator pattern in which 'borrowable' functionality is added to existing library items (books and videos). /* * Real-World Decorator Design Pattern. */ ...分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net
Definition
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
Participants
The classes and/or objects participating in this pattern are:
- Component (LibraryItem)
- Defines the interface for objects that can have responsibilities added to them dynamically.
- ConcreteComponent (Book, Video)
- Defines an object to which additional responsibilities can be attached.
- Decorator (Decorator)
- Maintains a reference to a Component object and defines an interface that conforms to Component's interface.
- ConcreteDecorator (Borrowable)
- Adds responsibilities to the component.
Sample Code in C#
This structural code demonstrates the Decorator pattern which dynamically adds extra functionality to an existing object.
/* * Structural Decorator Design Pattern. */ namespace Decorator.Sample { using System; /// <summary> /// Startup class for Structural Decorator Design Pattern. /// </summary> internal static class Program { #region Methods /// <summary> /// Entry point into console application. /// </summary> private static void Main() { // Create ConcreteComponent and two Decorators. var c = new ConcreteComponent(); var d1 = new ConcreteDecoratorA(); var d2 = new ConcreteDecoratorB(); // Link decorators. d1.SetComponent(c); d2.SetComponent(d1); d2.Operation(); } #endregion } /// <summary> /// The 'Component' abstract class. /// </summary> internal abstract class Component { #region Public Methods and Operators /// <summary> /// The operation. /// </summary> public abstract void Operation(); #endregion } /// <summary> /// The 'ConcreteComponent' class. /// </summary> internal class ConcreteComponent : Component { #region Public Methods and Operators /// <summary> /// The operation. /// </summary> public override void Operation() { Console.WriteLine("ConcreteComponent.Operation()"); } #endregion } /// <summary> /// The 'Decorator' abstract class. /// </summary> internal abstract class Decorator : Component { #region Fields /// <summary> /// The component. /// </summary> protected Component Component; #endregion #region Public Methods and Operators /// <summary> /// The operation. /// </summary> public override void Operation() { Component?.Operation(); } /// <summary> /// Set component. /// </summary> /// <param name="component"> /// The component. /// </param> public void SetComponent(Component component) { Component = component; } #endregion } /// <summary> /// The 'ConcreteDecoratorA' class. /// </summary> internal class ConcreteDecoratorA : Decorator { #region Public Methods and Operators /// <summary> /// The operation. /// </summary> public override void Operation() { base.Operation(); Console.WriteLine("ConcreteDecoratorA.Operation()"); } #endregion } /// <summary> /// The 'ConcreteDecoratorB' class. /// </summary> internal class ConcreteDecoratorB : Decorator { #region Public Methods and Operators /// <summary> /// The operation. /// </summary> public override void Operation() { base.Operation(); AddedBehavior(); Console.WriteLine("ConcreteDecoratorB.Operation()"); } #endregion #region Methods /// <summary> /// The added behavior. /// </summary> private void AddedBehavior() { } #endregion } } // Output: /* ConcreteComponent.Operation() ConcreteDecoratorA.Operation() ConcreteDecoratorB.Operation() */
This real-world code demonstrates the Decorator pattern in which 'borrowable' functionality is added to existing library items (books and videos).
/* * Real-World Decorator Design Pattern. */ namespace Decorator.RealWorld { using System; using System.Collections.Generic; /// <summary> /// Startup class for Real-World Decorator Design Pattern. /// </summary> internal static class Program { #region Methods /// <summary> /// Entry point into console application. /// </summary> private static void Main() { // Create book. var book = new Book("Worley", "Inside ASP.NET", 10); book.Display(); // Create video. var video = new Video("Spielberg", "Jaws", 23, 92); video.Display(); // Make video borrowable, then borrow and display. Console.WriteLine("Making video borrowable:"); var borrowVideo = new Borrowable(video); borrowVideo.BorrowItem("Customer #1"); borrowVideo.BorrowItem("Customer #2"); borrowVideo.Display(); } #endregion } /// <summary> /// The 'Component' abstract class. /// </summary> internal abstract class LibraryItem { #region Public Properties /// <summary> /// Gets or sets the number of copies. /// </summary> public int NumCopies { get; set; } #endregion #region Public Methods and Operators /// <summary> /// Display. /// </summary> public abstract void Display(); #endregion } /// <summary> /// The 'ConcreteComponent' class. /// </summary> internal class Book : LibraryItem { #region Fields /// <summary> /// The author. /// </summary> private readonly string _author; /// <summary> /// The title. /// </summary> private readonly string _title; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="Book"/> class. /// </summary> /// <param name="author"> /// The author. /// </param> /// <param name="title"> /// The title. /// </param> /// <param name="numCopies"> /// The number of copies. /// </param> public Book(string author, string title, int numCopies) { _author = author; _title = title; NumCopies = numCopies; } #endregion #region Public Methods and Operators /// <summary> /// Display. /// </summary> public override void Display() { Console.WriteLine("\nBook ------ "); Console.WriteLine(" Author: {0}", _author); Console.WriteLine(" Title: {0}", _title); Console.WriteLine(" # Copies: {0}", NumCopies); } #endregion } /// <summary> /// The 'ConcreteComponent' class. /// </summary> internal class Video : LibraryItem { #region Fields /// <summary> /// The director. /// </summary> private readonly string _director; /// <summary> /// The play time. /// </summary> private readonly int _playTime; /// <summary> /// The title. /// </summary> private readonly string _title; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="Video"/> class. /// </summary> /// <param name="director"> /// The director. /// </param> /// <param name="title"> /// The title. /// </param> /// <param name="numCopies"> /// The number of copies. /// </param> /// <param name="playTime"> /// The play time. /// </param> public Video(string director, string title, int numCopies, int playTime) { _director = director; _title = title; NumCopies = numCopies; _playTime = playTime; } #endregion #region Public Methods and Operators /// <summary> /// Display. /// </summary> public override void Display() { Console.WriteLine("\nVideo ------ "); Console.WriteLine(" Director: {0}", _director); Console.WriteLine(" Title: {0}", _title); Console.WriteLine(" # Copies: {0}", NumCopies); Console.WriteLine(" Playtime: {0}\n", _playTime); } #endregion } /// <summary> /// The 'Decorator' abstract class. /// </summary> internal abstract class Decorator : LibraryItem { #region Fields /// <summary> /// The library item. /// </summary> protected readonly LibraryItem LibraryItem; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="SampleDecorator"/> class. /// </summary> /// <param name="libraryItem"> /// The library item. /// </param> protected Decorator(LibraryItem libraryItem) { LibraryItem = libraryItem; } #endregion #region Public Methods and Operators /// <summary> /// Display. /// </summary> public override void Display() { LibraryItem.Display(); } #endregion } /// <summary> /// The 'ConcreteDecorator' class. /// </summary> internal class Borrowable : Decorator { #region Fields /// <summary> /// The borrowers. /// </summary> protected readonly List<string> Borrowers = new List<string>(); #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="Borrowable"/> class. /// </summary> /// <param name="libraryItem"> /// The library item. /// </param> public Borrowable(LibraryItem libraryItem) : base(libraryItem) { } #endregion #region Public Methods and Operators /// <summary> /// The borrow item. /// </summary> /// <param name="name"> /// The name. /// </param> public void BorrowItem(string name) { Borrowers.Add(name); LibraryItem.NumCopies--; } /// <summary> /// Display. /// </summary> public override void Display() { base.Display(); foreach (string borrower in Borrowers) { Console.WriteLine(" borrower: " + borrower); } } /// <summary> /// The return item. /// </summary> /// <param name="name"> /// The name. /// </param> public void ReturnItem(string name) { Borrowers.Remove(name); LibraryItem.NumCopies++; } #endregion } } // Output: /* Book ------ Author: Worley Title: Inside ASP.NET # Copies: 10 Video ------ Director: Spielberg Title: Jaws # Copies: 23 Playtime: 92 Making video borrowable: Video ------ Director: Spielberg Title: Jaws # Copies: 21 Playtime: 92 borrower: Customer #1 borrower: Customer #2 */
- Component (LibraryItem)
-
python decorator. decorator_Python中decorator使用实例
2020-12-08 13:02:14在我以前介绍 Python 2.4 特性的Blog中已经介绍过了decorator了,不过,那时是照猫画虎,现在再仔细描述一下它的使用。关于decorator的详细介绍在 Python 2.4中的What's new中已经有介绍,大家可以看一下。如何调用...在我以前介绍 Python 2.4 特性的Blog中已经介绍过了decorator了,不过,那时是照猫画虎,现在再仔细描述一下它的使用。
关于decorator的详细介绍在 Python 2.4中的What's new中已经有介绍,大家可以看一下。
如何调用decorator
基本上调用decorator有两种形式
第一种:
复制代码 代码如下:
@A
def f ():
这种形式是decorator不带参数的写法。最终 Python 会处理为:
复制代码 代码如下:
f = A(f)
还可以扩展成:
复制代码 代码如下:
@A
@B
@C
def f ():
最终 Python 会处理为:
复制代码 代码如下:
f = A(B(C(f)))
注:文档上写的是@A @B @C的形式,但实际上是不行的,要写成多行。而且执行顺序是按函数调用顺序来的,先最下面的C,然后是B,然后是A。因此,如果decorator有顺序话,一定要注意:先要执行的放在最下面,最后执行的放在最上面。(应该不存在这种倒序的关系)
第二种:
复制代码 代码如下:
@A(args)
def f ():
这种形式是decorator带参数的写法。那么 Python 会处理为:
复制代码 代码如下:
def f():
_deco = A(args)
f = _deco(f)
可以看出, Python 会先执行A(args)得到一个decorator函数,然后再按与第一种一样的方式进行处理。
decorator函数的定义
每一个decorator都对应有相应的函数,它要对后面的函数进行处理,要么返回原来的函数对象,要么返回一个新的函数对象。请注意,decorator只用来处理函数和类方法。
第一种:
针对于第一种调用形式
复制代码 代码如下:
def A(func):
#处理func
#如func.attr='decorated'
return func
@A
def f(args):pass
上面是对func处理后,仍返回原函数对象。这个decorator函数的参数为要处理的函数。如果要返回一个新的函数,可以为:
复制代码 代码如下:
def A(func):
def new_func(args):
#做一些额外的工作
return func(args) #调用原函数继续进行处理
return new_func
@A
def f(args):pass
要注意 new_func的定义形式要与待处理的函数相同,因此还可以写得通用一些,如:
复制代码 代码如下:
def A(func):
def new_func(*args, **argkw):
#做一些额外的工作
return func(*args, **argkw) #调用原函数继续进行处理
return new_func
@A
def f(args):pass
可以看出,在A中定义了新的函数,然后A返回这个新的函数。在新函数中,先处理一些事情,比如对参数进行检查,或做一些其它的工作,然后再调原始的函数进行处理。这种模式可以看成,在调用函数前,通过使用decorator技术,可以在调用函数之前进行了一些处理。如果你想在调用函数之后进行一些处理,或者再进一步,在调用函数之后,根据函数的返回值进行一些处理可以写成这样:
复制代码 代码如下:
def A(func):
def new_func(*args, **argkw):
result = func(*args, **argkw) #调用原函数继续进行处理
if result:
#做一些额外的工作
return new_result
else:
return result
return new_func
@A
def f(args):pass
第二种:
针对第二种调用形式
在文档上说,如果你的decorator在调用时使用了参数,那么你的decorator函数只会使用这些参数进行调用,因此你需要返回一个新的decorator函数,这样就与第一种形式一致了。
复制代码 代码如下:
def A(arg):
def _A(func):
def new_func(args):
#做一些额外的工作
return func(args)
return new_func
return _A
@A(arg)
def f(args):pass
可以看出A(arg)返回了一个新的 decorator _A。
decorator的应用场景
不过我也一直在想,到底decorator的魔力是什么?适合在哪些场合呢?是否我需要使用它呢?
decorator的魔力就是它可以对所修饰的函数进行加工。那么这种加工是在不改变原来函数代码的情况下进行的。有点象我知道那么一点点的AOP(面向方面编程)的想法。
它适合的场合我能想到的列举出下:
1.象文档中所说,最初是为了使调用staticmethod和classmethod这样的方法更方便
2.在某些函数执行前做一些工作,如web开发中,许多函数在调用前需要先检查一下用户是否已经登录,然后才能调用
3.在某此函数执行后做一些工作,如调用完毕后,根据返回状态写日志
4.做参数检查
可能还有许多,你可以自由发挥想象
那么我需要用它吗?
我想那要看你了。不过,我想在某些情况下,使用decorator可以增加程序的灵活性,减少耦合度。比如前面所说的用户登录检查。的确可以写一个通用的登录检查函数,然后在每个函数中进行调用。但这样会造成函数不够灵活,而且增加了与其它函数之间的结合程度。如果用户登录检查功能有所修改,比如返回值的判断发生了变化,有可能每个用到它的函数都要修改。而使用decorator不会造成这一问题。同时使用decorator的语法也使得代码简单,清晰(一但你熟悉它的语法的话)。当然你不使用它是可以的。不过,这种函数之间相互结合的方式,更符合搭积木的要求,它可以把函数功能进一步分解,使得功能足够简单和单一。然后再通过decorator的机制灵活的把相关的函数串成一个串,这么一想,还真是不错。比如下面:
复制代码 代码如下:
@A
@B
def account(args):pass
假设这是一个记帐处理函数,account只管记帐。但一个真正的记帐还有一些判断和处理,比如:B检查帐户状态,A记日志。这样的效果其实是先检查B、通过在A中的处理可以先执行account,然后再进行记日志的处理。象搭积木一样很方便,改起来也容易。甚至可以把account也写成decorator,而下面执行的函数是一个空函数。然后再通过配置文件等方法,将decorator的组合保存起来,就基本实现功能的组装化。是不是非常理想。
Python 带给人的创造力真是无穷啊!
-
decorator_Python Decorator示例
2020-07-14 13:24:52decoratorPython decorator is a function that helps to add some additional functionalities to an already defined function. Python decorator is very helpful to add functionality to a function that is im...