【发布时间】:2012-05-16 00:17:48
【问题描述】:
本来想问this question,后来发现之前已经想到了……
谷歌搜索我发现了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"""
但是,我不应该调用 init 吗?这是在 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 中)——而只需让超人被继承。 -
有更正链接的有用参考:amyboyle.ninja/Python-Inheritance
标签: python inheritance configparser