本來我想問問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/ –