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

倖福魔咒の 提交于 2019-12-05 11:45:51

问题


I have understood the basics of decorators and mixins. Decorators add a new functionality to an object without changing other object instances of the same class, while a mixin is a kind of multiple inheritance used to inherit from multiple parent classes.

Does it mean that decorators should be used when you'd need to modify only a single object instance and use mixins when you'd need a whole new class of objects. Or, is there something more to it that I might be missing? What can be real life use cases for both?


回答1:


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.



来源:https://stackoverflow.com/questions/30317965/python-use-of-decorators-v-s-mixins

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