继承和覆盖__init__在python中 [英] Inheritance and Overriding __init__ in python
本文介绍了继承和覆盖__init__在python中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在阅读深入Python",并且在有关类的章节中给出了以下示例:
I was reading 'Dive Into Python' and in the chapter on classes it gives this example:
class FileInfo(UserDict):
"store file metadata"
def __init__(self, filename=None):
UserDict.__init__(self)
self["name"] = filename
作者然后说,如果要覆盖__init__
方法,则必须使用正确的参数显式调用父__init__
.
The author then says that if you want to override the __init__
method, you must explicitly call the parent __init__
with the correct parameters.
- 如果该
FileInfo
类具有多个祖先类怎么办?- 是否必须显式调用所有祖先类的
__init__
方法?
- 是否必须显式调用所有祖先类的
- What if that
FileInfo
class had more than one ancestor class?- Do I have to explicitly call all of the ancestor classes'
__init__
methods?
- Do I have to explicitly call all of the ancestor classes'
推荐答案
关于子类-超类调用,本书有些过时了.在子类化内置类方面也有些过时.
The book is a bit dated with respect to subclass-superclass calling. It's also a little dated with respect to subclassing built-in classes.
如今看起来像这样:
class FileInfo(dict):
"""store file metadata"""
def __init__(self, filename=None):
super(FileInfo, self).__init__()
self["name"] = filename
请注意以下几点:
-
我们可以直接对内置类进行子类化,例如
dict
,list
,tuple
等.
super
函数负责跟踪此类的超类并在其中适当地调用函数.
The super
function handles tracking down this class's superclasses and calling functions in them appropriately.
这篇关于继承和覆盖__init__在python中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文