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

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


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.