What is the difference between Python decorators and the decorator pattern?

前端 未结 2 465
长发绾君心
长发绾君心 2020-12-12 21:20

What is the difference between “Python decorators” and the “decorator pattern”?

When should I use Python decorators, and when should I use the decorator pattern?

2条回答
  •  生来不讨喜
    2020-12-12 21:38

    Decorator Pattern - In object-oriented programming, the decorator pattern is a design pattern that allows behaviour to be added to an existing object dynamically. The decorator pattern can be used to extend (decorate) the functionality of a certain object at run-time, independently of other instances of the same class, provided some groundwork is done at design time.

    Decorators in Python - Despite the name, Python decorators are not an implementation of the decorator pattern. The decorator pattern is a design pattern used in statically typed object-oriented programming languages to allow functionality to be added to objects at run time; Python decorators add functionality to functions and methods at definition time, and thus are a higher-level construct than decorator-pattern classes.

    The decorator pattern itself is trivially implementable in Python, because the language is duck typed, and so is not usually considered as such. So in Python a decorator is any callable Python object that is used to modify a function, method or class definition.

    I hope I made the difference clear. Just in case you did not completely understand, please go through these links. You will come out more than clear at the end of it -

    • How to make a chain of function decorators?

    • Implementing the decorator pattern in Python

    • What is the difference between using decorators and extending a sub class by inheritance?

    • Python Class Decorator

    • PyWiki - Python Decorators - A detailed discourse

    • Python Decorators Made Easy

    • Source 1 & source 2

提交回复
热议问题