本文介绍了Python扩展 - 使用super()Python 3与Python 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最初我想问,但之后我发现它已经是之前的想法...

Originally I wanted to ask this question, but then I found it was already thought of before...

谷歌搜索我发现这个。以下适用于Python 3:

Googling around I found this example of extending configparser. The following works with Python 3:

$ python3
Python 3.2.3rc2 (default, Mar 21 2012, 06:59:51)
[GCC 4.6.3] on linux2
>>> from configparser import  SafeConfigParser
>>> class AmritaConfigParser(SafeConfigParser):
...     def __init_(self):
...         super().__init__()
...
>>> cfg = AmritaConfigParser()

但不是Python 2:

But not with Python 2:

>>> class AmritaConfigParser(SafeConfigParser):
...       def __init__(self):
...           super(SafeConfigParser).init()
...
>>> cfg = AmritaConfigParser()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __init__
TypeError: must be type, not classob

然后我读了一下Python New Class和Old Class样式(例如。
现在我想知道,我能做到:

Then I read a little bit on Python New Class vs. Old Class styles (e.g. here.And now I am wondering, I can do:

class MyConfigParser(ConfigParser.ConfigParser):
      def Write(self, fp):
          """override the module's original write funcition"""
          ....
      def MyWrite(self, fp):
          """Define new function and inherit all others"""

但是,我不应该调用init吗?这在Python 2中是等价的吗?

But, shouldn't I call init? Is this in Python 2 the equivalent:

 class AmritaConfigParser(ConfigParser.SafeConfigParser):
    #def __init__(self):
    #    super().__init__() # Python3 syntax, or rather, new style class syntax ...
    #
    # is this the equivalent of the above ?
    def __init__(self):
        ConfigParser.SafeConfigParser.__init__(self)


推荐答案


  • (不带参数)(以及 __ class __ ):

    super() -> same as super(__class__, self)
    

    因此对于新式类而言,这将是Python 2的等价物:

    so that would be the Python 2 equivalent for new-style classes:

    super(CurrentClass, self)
    


  • 您可以随时使用的旧式课程:

  • for old-style classes you can always use:

     class Classname(OldStyleParent):
        def __init__(self, *args, **kwargs):
            OldStyleParent.__init__(self, *args, **kwargs)
    


  • 这篇关于Python扩展 - 使用super()Python 3与Python 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 01:36