python super

关于super的作用:

https://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods
StackOverflow上的这个问题非常有价值,有1900+的star 作者举出了自己的例子,大意是代码不需要super也能实现这样的逻辑,为什么要无端引入super呢?下面都个1300+赞的回答,他的回答要点是:

  1. lets you avoid referring to the base class explicitly, which can be nice.
  2. But the main advantage comes with multiple inheritance, where all sorts of fun stuff can happen

回答中引用了这篇博文:
https://www.artima.com/weblogs/viewpost.jsp?thread=236275 这篇文章我暂时没有足够的时间去理解它。

第二个回答 https://stackoverflow.com/a/27134600/7360457 强调了:super的重要不在于避免写出父类,而是在于确保方法引用顺序(MRO)被调用,并且答主给出了代码解释。多继承时(如果不使用),第一个父类的__init__被调用了,但是第二类的__int__没有被调用,仅仅执行了一个。

我的结论:super在多继承时扮演着非常重要的角色,多继承时,super函数告诉我们会MRO的解析顺序列表中查找下个父类的方法,供子类去使用。每执行一次,就对MRO调用了一次next

http://www.cnblogs.com/lovemo1314/archive/2011/05/03/2035005.html
博客园的这篇文章也提到了为什么要用super?

很好理解去从父类中继承(属性或者方法),但是我不理解为什么要继承自身?

class Mmap(object):
    """
    Convenience class for opening a read-only memory map for a file path.
    """

    def __init__(self, filename):
        super(Mmap, self).__init__()   # 继承父类的方法
        self._filename = filename
        self._f = None
        self._mmap = None

    def __enter__(self):
        self._f = open(self._filename, "rb")
        self._mmap = mmap.mmap(self._f.fileno(), 0, access=mmap.ACCESS_READ)
        return self._mmap

    def __exit__(self, type, value, traceback):
        self._mmap.close()
        self._f.close()

解读:

super(Mmap, self).init() 的解释:https://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods

原文地址:https://www.cnblogs.com/crb912/p/9713430.html