grandparent method with super

attn.steven.kuo at gmail.com attn.steven.kuo at gmail.com
Fri Apr 6 00:05:25 CEST 2007


On Apr 5, 2:13 pm, Martin Manns <mma... at gmx.de> wrote:
> On Thu, 5 Apr 2007 16:55:38 -0400
>
>
>
> "John Clark" <claj... at mac.com> wrote:
> > >That works, but when I replace A with something else, I do not get
> > >the
> > grandparent anymore
> > >without changing all the method calls. Basically, I would like to
> > >call the
> > method m in the first
> > >grandparent of D.
>
> > >Martin
>
> > I think the problem you may run into is with the term "first
> > grandparent" - when you look at the method resolution order of the
> > class D, you will find that the MRO goes "D, C, B, A"... I think it's
> > going to be difficult to figure out where the "first grandparent" is
> > in the MRO.
>
> > For example:
>
> > class A(object):
> >    def m(self):
> >            pass
> > class B(A):
> >    def m(self):
> >            pass
> > class C(B):
> >    def m(self):
> >            pass
> > class D(A):
> >    def m(self):
> >            pass
> > class E(C,D):
> >    def m(self):
> >            firstgrandparent(E,self).m() #Should call B.m
> > class F(D,C):
> >    def m(self):
> >            firstgrandparent(F,self).m() # Should call F.m
>
> > The mro for class E is going to be "E,C,B,D,A" where as the mro for
> > class F is going to be "F,D,C,B,A".  However, the first grandparent
> > for E should be B, where as the first grandparent for F should be A.
>
> > Because the MRO isn't just a depth first traversal, the term "first
> > grandparent" gets tricky to define...
>
> Not really. The first grandparent would be the first occurrence in the
> list from left to right, which satisfies the requirement that its
> shortest path to the current class is 2.
>
> The only problem: How do I get it?
>
> Martin



class E(C,D):
    def m(self):
        for cls in E.__mro__:
            if cls != E and cls not in E.__bases__:
                cls.m(self)
                break


... but it's probably better that you
rethink your class hierarchy.

--
Hope this helps,
Steven




More information about the Python-list mailing list