什么是mixin,为什么有用? [英] What is a mixin, and why are they useful?

查看:647
本文介绍了什么是mixin,为什么有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Mark Lutz在"编程Python 中,马克·卢兹(Mark Lutz)提到"mixins".我来自C/C ++/C#背景,以前没有听说过这个词.什么是mixin?

In "Programming Python", Mark Lutz mentions "mixins". I'm from a C/C++/C# background and I have not heard the term before. What is a mixin?

Reading between the lines of this example (which I've linked to because it's quite long), I'm presuming it's a case of using multiple inheritance to extend a class as opposed to 'proper' subclassing. Is this right?

为什么我要这样做而不是将新功能放入子类中?因此,为什么混合/多重继承方法比使用组合更好?

Why would I want to do that rather than put the new functionality into a subclass? For that matter, why would a mixin/multiple inheritance approach be better than using composition?

什么将mixin与多重继承区分开?这只是语义问题吗?

What separates a mixin from multiple inheritance? Is it just a matter of semantics?

推荐答案

mixin是一种特殊的多重继承.使用mixin的主要情况有两种:

A mixin is a special kind of multiple inheritance. There are two main situations where mixins are used:

  1. 您要为一个类提供很多可选功能.
  2. 您想在许多不同的类中使用一项特定功能.

以第一个示例为例,请考虑 werkzeug的请求和响应系统.我可以说一个普通的旧请求对象:

For an example of number one, consider werkzeug's request and response system. I can make a plain old request object by saying:

from werkzeug import BaseRequest

class Request(BaseRequest):
    pass

如果我想添加接受标头支持,我会做到

If I want to add accept header support, I would make that

from werkzeug import BaseRequest, AcceptMixin

class Request(AcceptMixin, BaseRequest):
    pass

如果我想创建一个支持接受标头,etags,身份验证和用户代理支持的请求对象,我可以这样做:

If I wanted to make a request object that supports accept headers, etags, authentication, and user agent support, I could do this:

from werkzeug import BaseRequest, AcceptMixin, ETagRequestMixin, UserAgentMixin, AuthenticationMixin

class Request(AcceptMixin, ETagRequestMixin, UserAgentMixin, AuthenticationMixin, BaseRequest):
    pass

差别是细微的,但是在上面的示例中,mixin类并不是独立存在的.在更传统的多重继承中,例如AuthenticationMixin可能更像Authenticator.也就是说,该类可能会设计为独立存在.

The difference is subtle, but in the above examples, the mixin classes weren't made to stand on their own. In more traditional multiple inheritance, the AuthenticationMixin (for example) would probably be something more like Authenticator. That is, the class would probably be designed to stand on its own.

这篇关于什么是mixin,为什么有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆