lie*_*ewl 124 python overriding superclass
我正在阅读'Dive Into Python',并在关于类的章节中给出了这个例子:
class FileInfo(UserDict):
"store file metadata"
def __init__(self, filename=None):
UserDict.__init__(self)
self["name"] = filename
Run Code Online (Sandbox Code Playgroud)
然后,作者说如果要覆盖该__init__
方法,则必须__init__
使用正确的参数显式调用父级.
FileInfo
班有一个以上的祖先课怎么办?
__init__
方法? S.L*_*ott 149
这本书对于子类 - 超类调用有点过时了.对于子类内置类,它也有点过时了.
现在看起来像这样.
class FileInfo(dict):
"""store file metadata"""
def __init__(self, filename=None):
super(FileInfo, self).__init__()
self["name"] = filename
Run Code Online (Sandbox Code Playgroud)
请注意以下内容.
我们可以直接继承内建类,如dict
,list
,tuple
,等.
该super
函数处理跟踪此类的超类并适当调用其中的函数.
小智 16
在您需要继承的每个类中,您可以在启动子类时运行需要init'd的每个类的循环...可以更好地理解可以复制的示例...
class Female_Grandparent:
def __init__(self):
self.grandma_name = 'Grandma'
class Male_Grandparent:
def __init__(self):
self.grandpa_name = 'Grandpa'
class Parent(Female_Grandparent, Male_Grandparent):
def __init__(self):
Female_Grandparent.__init__(self)
Male_Grandparent.__init__(self)
self.parent_name = 'Parent Class'
class Child(Parent):
def __init__(self):
Parent.__init__(self)
#---------------------------------------------------------------------------------------#
for cls in Parent.__bases__: # This block grabs the classes of the child
cls.__init__(self) # class (which is named 'Parent' in this case),
# and iterates through them, initiating each one.
# The result is that each parent, of each child,
# is automatically handled upon initiation of the
# dependent class. WOOT WOOT! :D
#---------------------------------------------------------------------------------------#
g = Female_Grandparent()
print g.grandma_name
p = Parent()
print p.grandma_name
child = Child()
print child.grandma_name
Run Code Online (Sandbox Code Playgroud)
sth*_*sth 14
您实际上不必调用__init__
基类的方法,但是您通常希望这样做,因为基类将在那里进行一些重要的初始化,这是其他类方法工作所需要的.
对于其他方法,它取决于您的意图.如果您只想在基类行为中添加一些内容,则需要在自己的代码之外调用基类方法.如果要从根本上改变行为,可能不会调用基类的方法并直接在派生类中实现所有功能.