本来我想问问this question,但后来我发现的时候,已经想到过的......Python的延伸 - 使用超()的Python 3比Python的2
周围的Googling我发现extending configparser这个例子。与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:
>>> 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的新类与旧类样式一点点(如here 现在我。我想,我可以这样做:
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"""
但是,我不应该叫初始化这是在Python 2等价的:?
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)
在你的榜样,你不需要定义一个'__init __()'的子类,如果它是所有调用超类'__init __()'(以Python 2或3) - 而是让超级继承。 – martineau
有用的参考资料:http://amyboyle.ninja/Python-Inheritance/ –