当我(错误?)使用super时,我的方法不会被调用

时间:2014-05-10 18:46:12

标签: python-2.7 multiple-inheritance super new-style-class

class Document(object):
    def __init__(self,filename):
        self.filename = filename
        self.edits    = 0

    def write(self,content):
        print "D.write"
        fd = open(self.filename,"w")
        fd.write(content)
        fd.close()
        self.edits += 1

class HTMLDocument(Document):
    def edit(self,content):
        print "HTMLD.edit"
        self.validate(content)
        # Document.write(self,content)
        super(HTMLDocument,self).write(content)

    def validate(self,content):
        return True

class UpperCaseDocument(Document):
    def edit(self,content):
        print "UCD.edit"
        content = content.upper()
        # Document.write(self,content)
        super(UpperCaseDocument,self).write(content)        

class UpperCaseHTMLDocument(HTMLDocument,UpperCaseDocument):
    def edit(self,content):
        super(UpperCaseHTMLDocument,self).edit(content)
        # HTMLDocument.edit(self,content)        
        # UpperCaseDocument.edit(self,content)

index   = UpperCaseHTMLDocument("index.html")
content = "<html> hi there ! </html>"
# First Edit
index.edit(content)
# Second Edit
# content.replace("t","z")
# index.edit(content)
print index.edits

### output

>>> HTMLD.edit
D.write
1
>>>

没有&#34; UCD.edit&#34;在输出中,这意味着不会调用UpperCaseDocument.edit。我错过了什么?

感谢您的帮助。

(如果您认为super只会调用一个baseclasse方法,请使用以下代码进行测试:

class A(object):
    def save(self):
        print "A saves"

class B(A):
    def save(self):
        self.validate()
        print "B validates and saves"
        # A.save(self)
        super(B,self).save()

    def validate(self):
        return True

class C(A):
    def save(self):
        self.validate()
        print "C validates and saves"
        # A.save(self)
        super(C,self).save()

    def validate(self):
        return True

class D(B,C):
    def save(self):
        print "D validates and saves"
        self.validate()
        # B.save(self)
        # C.save(self)
        super(D,self).save()

    def validate(self):
        return True


d = D()
d.save()    


# output 
>>> D validates and saves
B validates and saves
C validates and saves
A saves
>>> 

# Both B.save and C.save get called from super.

0 个答案:

没有答案