Python扩展-使用super()Python 3 vs Python 2
发布于 2021-01-29 15:06:09
本来我想问这个问题,但是后来我发现它已经被想到了……
在谷歌搜索中,我发现了扩展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 New Class vs. Old
Class样式的信息(例如,在这里。现在我很想知道,我可以这样做:
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)
关注者
0
被浏览
83
1 个回答
-
super()
(不带参数)在Python 3中(以及__class__
)引入:super() -> same as super(__class__, self)
这样就相当于新类的Python 2:
super(CurrentClass, self)
- 对于老式类,您可以始终使用:
class Classname(OldStyleParent): def __init__(self, *args, **kwargs): OldStyleParent.__init__(self, *args, **kwargs)