2 minute read

In the last posting, I’ve written about the range. In Python, the range object is an implementation of collections.abc.Sequence. Let’s take a look at what it is.

collections.abc.Sequence

abc?

Here “abc” is “Abstract Base Class”.

Abstract class

Quoting from the Wikipedia,

In programming languages, an abstract type is a type in a nominative type system that cannot be instantiated directly.

Two new terms are here. “nominative type system” and “instantiate”.

Again quoting from the Wiki page,

Nominal typing means that two variables are type-compatible if and only if their declarations name the same type.

To understand this with an example, this article is great to understand in a programming context.

In a nutshell, “Nominal typing” raises an error if we place a different type of variable to the expected type even though the difference is just the name of the type.

On the other hand, “Structural typing” says it’s okay. Once we modify the content, it will raise an error.

“Instantiation” in Python is creating an instance from a class definition.

class foo:
  ...

f = foo()

This is a side note from the Python official document.

Some of the mixin methods, such as iter(), reversed() and index(), make repeated calls to the underlying getitem() method. Consequently, if getitem() is implemented with constant access speed, the mixin methods will have linear performance; however, if the underlying method is linear (as it would be with a linked list), the mixins will have quadratic performance and will likely need to be overridden.

mixin?

For me, the multiple inheritance concept is more clear than mixin. For example, this is the inheritance in Python.

class Animal(): 
  def sound(self): 
    return ""


class Duck(Animal): 
  def sound(self): 
    return "quack"


class Dog(Animal): 
  pass 

duck = Duck()
duck.sound()  # 'quack'

dog = Dog()
dog.sound()  # ''

The child class inherits its parent class’s function and member variables.

Multiple inheritances are having multiple classes as parents. However, in practice, it’s super brittle to use multiple inheritances. In the community, it’s not the recommended way to design classes.

Mixin wants to address the inefficiency in single inheritance and the difficulty of multiple inheritances.

The mixins can offer rich behaviors to the target class. We expect those mixins will not be instantiated by themselves.

The concept of mixins is very similar to the multiple inheritances.

We want to gain advantages of the multiple inheritances and avoid the complexity.

Glossary “Sequence”

  • Supports efficient element access using integer indices via the __getitem__() special method and defines a __len__() method that returns the length of the sequence.
  • Built-in sequence types are list, str, tuple, and bytes
  • dict also supports __getitem__() and __len__() but is considered a mapping because the lookups using arbitrary immutable keys rather than integers

Reference

Leave a comment