i playing classes see how mro works in python3. got main idea: methods resolved left right, depth first , if there common parent, it's @ end.
here apparently quite simple not behave expect:
class a(object): def f(self): print("calling a") print("a") class b(a): def f(self): print("calling b") super(b, self).f() print("b") class c(a): def f(self): print("calling c") super(c, self).f() print("c") class d(b,c): def f(self): print("calling d") super(d, self).f() print("d") d=d() d.f() now, since mro d -> b -> c -> a expect super call b.f prints:
calling d calling b calling a b d but call c.f too:
calling d calling b calling c calling a c b d why that?
the reason expect c.f not called since b method f, resolution should stop. case if c not inherit a:
class a(object): def f(self): print("calling a") print("a") class b(a): def f(self): print("calling b") super(b, self).f() print("b") class c(): def f(self): print("calling c") super(c, self).f() print("c") class d(b,c): def f(self): print("calling d") super(d, self).f() print("d") d=d() d.f() # prints: # calling d # calling b # calling # # b # d
i think it's important mention super doesn't call "parent-class" "next class in mro".
you said yourself, mro d -> b -> c -> a d. super in d.f resolve b, super in b.f resolve c , super in c.f resolve a.
if need further information there several ressources (with different interpretations usefulness of super) avaiable:
Comments
Post a Comment