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

前端 未结 4 1775
自闭症患者
自闭症患者 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:40

    Note This is a terrible "solution", I post it only to make sure you don't do this at home!
    I repeat: do not do this

    One may think about using this mixin

    class Super(object):
        def super(self):
            return super(self.__class__, self)
    

    to obtain a self.super():

    class A(object, Super):
        def __init__(self):
            print "A"
    
    class B(A):
        def __init__(self):
            print "B"
            self.super().__init__()
    

    yielding:

     >>> a = A()
     A
     >>> b = B()
     B
     A
    

    But beware: This self.super() is not equivalent to super(B, self) - if A also called self.super().__init__(), the construction of a B would cause the A constructor to call itself indefinitely, since self.__class__ will remain B. This is due to the lack of the __class__ mentioned in the accepted answer. You can possibly work around this issue with a hidden state machine or a sophisticated metaclass that e.g. checks the actual class's position in self.__class__.mro(), but is it really worth it? Probably not...

提交回复
热议问题