Python rozszerzający się o - używając super () Python 3 vs Python 2
Pierwotnie chciałem zapytaćto pytanie, ale potem odkryłem, że już wcześniej o tym myślałem ...
Googling wokół znalazłem ten przykładrozszerzenie configparser. Poniższe działa z Pythonem 3:
<code>$ 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() </code>
Ale nie w Pythonie 2:
<code>>>> 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 </code>
Potem przeczytałem trochę o stylach Python New Class vs. Old Class (np.tutaj. A teraz zastanawiam się, mogę to zrobić:
<code>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""" </code>
Ale czy nie powinienem zadzwonić do init? Czy w Pythonie 2 jest to odpowiednik:
<code> 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) </code>