问题描述
我了解装饰器和mixin的基础知识.装饰器在不更改同一类的其他对象实例的情况下向对象添加了新功能,而mixin是一种用于从多个父类继承的多重继承.
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?
推荐答案
在我看来,当您有一些应该具有相同功能的不同类时,需要使用mixins.
In my opinion, you need mixins when you have a few different classes that should have same functionality.
使用mixin的好例子是Django的基于类的视图.例如,您有几个不同的类:FormView,TemplateView,ListView.它们都具有一项类似的功能:它们必须呈现模板.这些类中的每一个都有一个mixin,它添加了模板渲染所需的方法.
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.
另一个示例是是否需要为返回JSON结果的API添加类.它也可以从View类的基类继承.您只需跳过模板mixin,然后定义所需的内容(并可能编写自己的mixin进行JSON编码).
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).
此外,您可以覆盖mixins中建议的某些方法,这些方法使您可以针对本地情况修改通用代码的某些部分.都是关于OOP的,伙计!
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!
长话短说: mixins添加了新功能.
装饰器用于修改现有功能.例如,如果您需要记录类中方法返回的内容.正确的选择是装饰器(已添加到适当的方法中).
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.
这篇关于Python:使用装饰器v/s mixins吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!