Nguyên Tôi muốn hỏi this question, nhưng sau đó tôi thấy nó đã được nghĩ đến trước đây ...Python mở rộng với - sử dụng siêu() Python 3 vs Python 2
Googling xung quanh tôi thấy ví dụ này của extending configparser. Các công trình sau đây với 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()
Nhưng không phải với 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
Sau đó, tôi đọc một chút về Python New Class vs phong cách Old Class (ví dụ here Và bây giờ tôi. là băn khoăn, tôi có thể làm:
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"""
Nhưng, tôi không nên gọi init đây có phải là bằng Python 2 tương đương với:
012.351.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)
Trong ví dụ của bạn, bạn không cần phải xác định một '__init __() 'trong subclass nếu tất cả nó làm là gọi lớp siêu' __init __() '(trong hoặc Python 2 hoặc 3) - thay vì chỉ để cho siêu được kế thừa. – martineau
Tham khảo hữu ích: http://amyboyle.ninja/Python-Inheritance/ –