Can I use Python 3 super() in Python 2.5.6?

前端 未结 4 1724
自闭症患者
自闭症患者 2021-01-07 23:10

Can I use clean Python 3 super() syntax in Python 2.5.6?
Maybe with some kind of __future__ import?

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-07 23:45

    I realize this question is old, and the selected answer may have been correct at the time, but it's no longer complete. You still can't use super() in 2.5.6, but python-future provides a back-ported implementation for 2.6+:

    Install python-future with:

    % pip install future
    

    The following shows the redefinition of super under builtins:

    % python
    ...
    >>> import sys
    >>> sys.version_info[:3]
    (2, 7, 9)
    >>>
    >>> super
    
    >>>
    >>> from builtins import *
    >>> super
    
    >>> super.__module__
    'future.builtins.newsuper'
    

    It can be used as follows:

    from builtins import super
    
    class Foo(object):
        def f(self):
            print('foo')
    
    class Bar(Foo):
        def f(self):
            super().f() # <- whoomp, there it is
            print('bar')
    
    b = Bar()
    b.f()
    

    which outputs

    foo
    bar
    

    If you use pylint, you can disable legacy warnings with the comment:

    # pylint: disable=missing-super-argument
    

提交回复
热议问题