Mixin 与继承

发布于 2024-07-19 08:20:31 字数 22 浏览 7 评论 0原文

mixin 和继承有什么区别?

What is the difference between a mixin and inheritance?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

国粹 2024-07-26 08:20:31

mixin 通常与多重继承一起使用。 所以,从这个意义上说,“没有区别”。

细节是 mixin 很少作为独立对象有用。

例如,假设您有一个名为“ColorAndDimension”的 mixin,它添加了颜色属性以及宽度和高度。

现在,您可以将 ColorAndDimension 添加到 Shape 类、Sprite 类、Car 类等。它们都将具有相同的接口(例如 get/setColor、get/setHeight/Width 等),

因此,在通用情况下 mixin 是继承。 但是你可以认为这是类在整个领域中的角色问题,即 mixin 是“主要”类还是只是一个 mixin。


编辑——只是为了澄清。

是的,用当今的现代行话来说,mixin 可以被认为是具有关联实现的接口。 它实际上只是使用普通、旧的、日常的类的普通、旧的、日常的多重继承。 这恰好是MI的一个具体应用。 大多数语言都不给 mixin 任何特殊的地位; 它只是一个被设计为“混合”的类,而不是独立使用。

A mixin is typically used with multiple inheritance. So, in that sense, there's "no difference".

The detail is that a mixin is rarely useful as a standalone object.

For example, say you have a mixin named "ColorAndDimension", which adds a color property and width and height.

Now, you could add ColorAndDimension to a, say, Shape class, a Sprite class, a Car class, etc. And they will all have the same interface (say get/setColor, get/setHeight/Width, etc.)

So, in the generic case a mixin IS inheritance. But you can argue it's a matter of the role of the class in the overall domain as to whether a mixin is a "primary" class or simply a mixin.


Edit -- just to clarify.

Yes, a mixin can be considered, in today's modern lingo, an Interface with an associated Implementation. It really is just plain, old, everyday multiple inheritance using a plain, old, everyday class. It just happens to be a specific application of MI. Most languages don't give a mixin any special status; it's just a class that was designed to be "mixed in", rather than used standalone.

や三分注定 2024-07-26 08:20:31

mixin 和继承有什么区别?

混合是一个基类,您可以继承它来提供附加功能。 伪代码示例:

class Mixin:
    def complex_method(self):
        return complex_functionality(self)

名称“mix-in”表示它旨在与其他代码混合。 因此,推论是您不会自行实例化混合类。 下面的对象没有数据,实例化它来调用complex_method是没有意义的。 (在这种情况下,您也可以只定义一个函数而不是一个类。)

>>> obj = Mixin()

混合经常与其他基类一起使用。

因此,混合是继承的子集或特殊情况。

使用混合相对于单一继承的优点是,您可以为该功能编写一次代码,然后在多个不同的类。 缺点是您可能需要在使用该功能的其他地方寻找该功能,因此最好通过将其放在附近来减轻该缺点。

我个人发现,在单一继承上使用混合是必要的,在这种情况下,我们对许多类似的代码进行单元测试,但测试用例是基于它们对基本案例的继承进行实例化的,这是使代码接近于手(并且在同一模块中),在不弄乱覆盖率数字的情况下,是从对象继承,并让子用例从通用测试用例基础和仅适用于它们的自定义基础继承。

Mixin 与抽象基类的比较和对比

两者都是父类的一种形式,不打算被实例化。

mixin提供功能,但无法直接使用它。 用户旨在通过(子)类使用它。

抽象基类提供接口,但没有可用的功能。 用户旨在创建由接口调用的功能。

class Abstraction(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def complex_method(self):
        return complex_functionality(self)

在这里,您无法实例化此对象,因为它需要一个子类来使用具体方法实现功能(尽管您可以从 super() 访问其中的功能):

>>> obj = Abstraction()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Abstraction with
abstract methods complex_method

在 Python 中,中的某些类>abc 模块是父类的示例,它们通过继承和必须由子类实现的抽象接口提供功能。 这些想法并不相互排斥。

总结

简而言之,混合只是一个您不会自行实例化的基类,并且通常用作多重继承中的辅助基类。

What is the difference between a mixin and inheritance?

A mix-in is a base class you can inherit from to provide additional functionality. Pseudocode example:

class Mixin:
    def complex_method(self):
        return complex_functionality(self)

The name "mix-in" indicates it is intended to be mixed in with other code. As such, the inference is that you would not instantiate the mix-in class on its own. The following object has no data, and it makes no sense to instantiate it to call complex_method. (You may as well just define a function instead of a class in that case.)

>>> obj = Mixin()

Frequently the mix-in is used with other base classes.

Therefore mixins are a subset, or special case, of inheritance.

The advantages of using a mix-in over single inheritance are that you can write code for the functionality one time, and then use the same functionality in multiple different classes. The disadvantage is that you may need to look for that functionality in other places than where it is used, so it is good to mitigate that disadvantage by keeping it close by.

I have personally found a mix-in necessary to use over single inheritance where we are unittesting a lot of similar code, but the test-cases are instantiated based on their inheritance of a base case, and the only way to keep the code close at hand (and in the same module), without messing with coverage numbers, is to inherit from object, and have the child cases inherit from both the universal test-case base and the custom base that only applies to them.

Mixins in Comparison and Contrast with Abstract Base Classes

Both are a form of parent class that is not intended to be instantiated.

A mixin provides functionality, but is unable to directly use it. A user is intended to use it through a (sub)class.

An abstract base class provides an interface, but without usable functionality. A user is intended to create the functionality called by the interface.

class Abstraction(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def complex_method(self):
        return complex_functionality(self)

Here you are prevented from instantiating this object because it requires a subclass to implement functionality with a concrete method (though you could access the functionality within from super()):

>>> obj = Abstraction()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Abstraction with
abstract methods complex_method

In Python, some classes in the abc module are examples of parent classes that both provide functionality through inheritance and abstract interfaces that must be implemented by the subclass. These ideas are not mutually exclusive.

Summary

Put simply, a mix-in is just a base class you wouldn't instantiate on its own, and typically used as a secondary base class in multiple inheritance.

清风不识月 2024-07-26 08:20:31

mix-in 是用于实现目的的(多重)继承的特定的、受限的情况; 某些语言(例如 Ruby)支持它,但不支持广义多重继承。

mix-in is a specific, restricted case of (multiple) inheritance used for implementation purposes; some languages (e.g. Ruby) support it without supporting generalized multiple inheritance.

你与昨日 2024-07-26 08:20:31

Mixin是一个抽象的概念,任何满足其要求的东西都可以被认为是mixin。

这是维基百科的定义。

在面向对象的编程语言中,mixin 是一个类,其中包含可供其他类使用的方法,而不必是这些其他类的父类。 其他类如何访问 mixin 的方法取决于语言。 Mixins 有时被描述为“包含”而不是“继承”。

简而言之,与继承的主要区别在于 mixins 不需要像下面那样具有“is-a”关系继承。

从实现的角度来看,您可以将其视为带有实现的接口。 例如,如果 Java 支持多重继承,则 Java 中的抽象类可以被视为 mixin。

Mixin is an abstract concept and anything that meets its requirement can be considered as a mixin.

Here is a definition from Wikipedia.

In object-oriented programming languages, a mixin is a class that contains methods for use by other classes without having to be the parent class of those other classes. How those other classes gain access to the mixin's methods depends on the language. Mixins are sometimes described as being "included" rather than "inherited".

In short, the key difference from an inheritance is that mix-ins does NOT need to have a "is-a" relationship like in inheritance.

From the implementation point of view, you can think it as an interface with implementations. For example, an abstract class in Java could be considered as a mixin if Java supported multiple inheritance.

守不住的情 2024-07-26 08:20:31

“mixin 是一个类的片段,因为它旨在与其他类或 mixin 组合在一起。” -DDJ

mixin 是一个类或代码片段,不适合独立使用,但您应该在另一个类中使用它。 将其组合为成员字段/变量或代码段。 我接触最多的是后者。 这比复制粘贴样板代码要好一点。

这是一篇介绍该主题的精彩 DDJ 文章。

《半条命 2》/ “Source”SDK 是 C++ mixins 的一个很好的例子。 在该环境中,宏定义了相当大的代码块,可以添加这些代码块来为类提供特定的“风味”或功能。

查看源 wiki 示例:创作逻辑实体。 在示例代码中,DECLARE_CLASS 宏可以被视为混合。 Source SDK 广泛使用 mixin 来标准化数据访问代码并将行为归因于实体。

"A mixin is a fragment of a class in the sense that it is intended to be composed with other classes or mixins." -DDJ

A mixin is a class or code fragment which is not intended for stand-alone use, but instead you're supposed to use it inside of another class. Either composing it as a member field/variable or as a code segment. I have the most exposure to the later. It's a little better than copy-pasting boilerplate code.

Here's a great DDJ article that introduces the subject.

The Half-Life 2 / "Source" SDK is a great example of C++ mixins. In that environment macros define sizable blocks of code which can be added to give the class a specific "flavor" or feature.

Look at the Source wiki example: Authoring a Logical Entity. In the example code the DECLARE_CLASS macro can be considered a mixin. Source SDK uses mixins extensively to standardize the data-access code and ascribe behaviors to entities.

不再见 2024-07-26 08:20:31

Mixins 广泛以更像“插件”的方式使用。

它们是相同的,但每个人都在不同的背景下。 通常,当我们谈论继承时,我们谈论的是单继承,而 mixin 是允许多重继承的构造。

这是一种在 OOP 世界中备受争议的语言结构,因为:

  • 必须解决它的歧义
  • 很多时候“mixin”类不能单独工作,并且可能与其他 mixin 发生冲突
  • 它可能会导致“钻石继承问题”,其中两个超类可以从同一个类继承

但除此之外,这是一个在各种语言和框架中使用的强大构造,一些例子是:

Mixins are vastly used in a more "plugin" like manner.

They are the same but in a different context each one of them. Usually when we talk about inheritance we are talking about SINGLE inheritance, and a mixin is a construct that allows MULTIPLE inheritance.

This is a language construct that is highly controversial in the OOP world because of:

  • The ambiguity that it must be resolved
  • A lot of the time "mixin" classes don't work on its own, and may conflict with other mixins
  • It can result in a "diamond inheritance problem", where two super classes can inherit from the same class

But that aside, is a powerful construct that's used in various languages and frameworks, some examples are:

2024-07-26 08:20:31

我认为需要注意的是,mixin 并不意味着继承。 根据维基百科, Mixin 是:

在面向对象的编程语言中,mixin 是一个类,
包含可供其他类使用的方法,而不必是
其他类的父类。 其他类别如何获得
对 mixin 方法的访问取决于语言。 混入是
有时被描述为“包含”而不是“继承”。

具体来说,在像 perl 这样的语言中,可以使用 Exporter 模块添加 mixins:

package Mixins;

use Exporter qw(import);
our @EXPORT_OK = qw(pity);

# assumes it will be mixed-in to a class with a _who_do_i_pity method
sub pity {
    my ($self) = @_;
    printf("I pity %s\n", $self->_who_do_i_pity('da foo'));
}

它可以混合到一次包含一个或多个方法的任何模块中:

package MrT

use Mixins qw(pity);

sub new {
    return bless({}, shift);
}

sub _who_do_i_pity {
    return 'da foo!'
}

然后在您的 MrT 模块可以这样使用:

use MrT;

MrT->new()->pity();

我知道这是一个荒谬的例子,但是,它明白了要点......

I think its important to note, that mixin doesn't imply inheritance. According to wikipedia, a Mixin is:

In object-oriented programming languages, a mixin is a class that
contains methods for use by other classes without having to be the
parent class of those other classes. How those other classes gain
access to the mixin's methods depends on the language. Mixins are
sometimes described as being "included" rather than "inherited".

Specifically, in a language like perl, mixins can be added using the Exporter module:

package Mixins;

use Exporter qw(import);
our @EXPORT_OK = qw(pity);

# assumes it will be mixed-in to a class with a _who_do_i_pity method
sub pity {
    my ($self) = @_;
    printf("I pity %s\n", $self->_who_do_i_pity('da foo'));
}

Which can be mixed-in to any module containing one, or more, method(s) at a time:

package MrT

use Mixins qw(pity);

sub new {
    return bless({}, shift);
}

sub _who_do_i_pity {
    return 'da foo!'
}

Then in your MrT module can be used thusly:

use MrT;

MrT->new()->pity();

I know its an absurd example, but, it gets the point across...

冷血 2024-07-26 08:20:31

通过多重继承,新类可以由多个超类组成。 您只能调用任何超类中定义的方法。

另一方面,mixin 是一个抽象子类,可用于专门化各种父类的行为。 Mixins 可以调用一个方法(例如 sayHello(): String),即使它们没有定义这样的方法。

mixin M {
    name: String
    defmethod greetings() { print sayHello() + " " + name}
}

正如您所看到的,您可以调用 sayHello(),即使它没有在任何地方定义。 如果将 mixin M 添加到类 C 中,则 C 应提供 sayHello() 方法。

With multiple inheritance, new class may be composed from multiple superclasses. You can call only methods defined in any of superclasses.

On the other hand, mixin is an abstract subclass that may be used to specialize the beavior of a variety of parent classes. Mixins may call a method (for example sayHello(): String) even though they do not define such a method.

mixin M {
    name: String
    defmethod greetings() { print sayHello() + " " + name}
}

As you see, you can call sayHello() even though it is not defined anywhere. If you add the mixin M to class C, the C should provide the sayHello() method.

表情可笑 2024-07-26 08:20:31

tl;dr

mixin 和多重继承具有相同的形式。 但有不同的语义:mixin 有提供函数实现的基本类。 对于继承,基类提供接口,子类具有实现。

但无论如何,在我看来,组合优于 mixin

tl;dr

mixin and multiple inheritance have the same form. But have different semantics: mixin has the basic classes provide the function implementation. For inheritance, base classes provide interface and subclass has the implementation.

But anyway, composition is preferred over mixin IMO

诠释孤独 2024-07-26 08:20:31

mixin是一个只有方法(功能)而没有属性(数据)的类,而继承中的父类既有属性(数据)又有方法(功能)。

A mixin is a class with methods(functionality) only and no attributes(data), while a parent class in inheritance has both attributes(data) and methods(functionality).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文