Python: Use of decorators v/s mixins? [closed]

前提是你 提交于 2019-12-04 01:18:55
Andrey Rusanov

In my opinion, you need mixins when you have a few different classes that should have same functionality.

Good examples of using mixins are Django's class-based views. For example, you have a few different classes: FormView, TemplateView, ListView. All of them have one similar piece of functionality: they have to render templates. Every one of these classes has a mixin, which adds methods required for template rendering.

Another example is if you needed to add a class for an API that returns a JSON result. It could also be inherited from a base, View class. You simply skip template mixins, and define what you need (and probably write your own mixin for JSON encoding).

Additionally, you may override some of methods proposed in mixins which allow you to modify some parts of common code for your local case. It's all about OOP, buddy!

Long story short: mixins add new functionalities.

Decorators are used to modify existing functionalities. For example, if you need to log what is returned from a method in your class. The right choice here is a decorator (added to appropriate methods).

Hope it is helpful. If not, please ask questions. I will update my response.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!