Which of the 4 ways to call super() in Python 3 to use?

后端 未结 2 1202
栀梦
栀梦 2020-12-05 14:17

I wonder when to use what flavour of Python 3 super().

Help on class super in module builtins:

class super(object)
 |  super() -> same as super(__class_         


        
2条回答
  •  遥遥无期
    2020-12-05 14:52

    Let's use the following classes for demonstration:

    class A(object):
        def m(self):
            print('m')
    
    class B(A): pass
    

    Unbound super object doesn't dispatch attribute access to class, you have to use descriptor protocol:

    >>> super(B).m
    Traceback (most recent call last):
      File "", line 1, in 
    AttributeError: 'super' object has no attribute 'm'
    >>> super(B).__get__(B(), B)
    , >
    

    super object bound to instance gives bound methods:

    >>> super(B, B()).m
    >
    >>> super(B, B()).m()
    m
    

    super object bound to class gives function (unbound methods in terms of Python 2):

    >>> super(B, B).m
    
    >>> super(B, B).m()
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: m() takes exactly 1 positional argument (0 given)
    >>> super(B, B).m(B())
    m
    

    See Michele Simionato's "Things to Know About Python Super" blog posts series (1, 2, 3) for more information

提交回复
热议问题