Python 文档中 "mixin methods" 的含义
Meaning of "mixin methods" in Python docs
python docs on collections.abc 有一个很好的摘要 table(下图),其中有一列名为“Mixin Methods”。我对本专栏与上一专栏的区别感到困惑。
是不是“抽象方法”可以定制,而“mixin方法”有一个特定的实现,在给定类型的所有类中都是固定的?如果是这样,我在哪里可以找到这些 mixin 方法中的内容?
非常感谢!
抽象 方法是您应该自己实现的方法,如果您从这些 classes 中的任何一个继承。例如:
class MyIter(collections.abc.Iterator):
# We must override __next__ because it's abstract in `Iterator`.
def __next__(self):
...
一个mixin是一个方法,其实现已经在superclass中提供了。所以你不需要覆盖 __iter__
,因为 Iterator
已经实现了它。
继续 Iterator
示例:Iterator
class 本身已实现 like this(稍微简化):
class Iterator(Iterable):
@abc.abstractmethod
def __next__(self):
pass
def __iter__(self):
return self
我们正在使用 abc.abstractmethod
to indicate that __next__
is abstract; if you forget to override it in your concrete implementation class, the decorator will cause an exception to be raised。
另一方面,__iter__
方法有一个简单的实现 returns self
,如 expected from iterator objects.
python docs on collections.abc 有一个很好的摘要 table(下图),其中有一列名为“Mixin Methods”。我对本专栏与上一专栏的区别感到困惑。
是不是“抽象方法”可以定制,而“mixin方法”有一个特定的实现,在给定类型的所有类中都是固定的?如果是这样,我在哪里可以找到这些 mixin 方法中的内容?
非常感谢!
抽象 方法是您应该自己实现的方法,如果您从这些 classes 中的任何一个继承。例如:
class MyIter(collections.abc.Iterator):
# We must override __next__ because it's abstract in `Iterator`.
def __next__(self):
...
一个mixin是一个方法,其实现已经在superclass中提供了。所以你不需要覆盖 __iter__
,因为 Iterator
已经实现了它。
继续 Iterator
示例:Iterator
class 本身已实现 like this(稍微简化):
class Iterator(Iterable):
@abc.abstractmethod
def __next__(self):
pass
def __iter__(self):
return self
我们正在使用 abc.abstractmethod
to indicate that __next__
is abstract; if you forget to override it in your concrete implementation class, the decorator will cause an exception to be raised。
另一方面,__iter__
方法有一个简单的实现 returns self
,如 expected from iterator objects.