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

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

问题描述

Python 编程"中,Mark Lutz提到混入".我来自 C/C++/C# 背景,我以前没有听说过这个词.什么是混入?

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?

混合和多重继承的区别是什么?只是语义问题吗?

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天全站免登陆