What's the purpose the hook method showing in a class definition?
jfong at ms4.hinet.net
jfong at ms4.hinet.net
Sun Oct 20 04:34:51 EDT 2019
Sibylle Koczian於 2019年10月20日星期日 UTC+8上午2時04分54秒寫道:
> Am 19.10.2019 um 13:11 schrieb jfong at ms4.hinet.net:
> > For the two examples below:
> > (1)
> >>>> class A:
> > ... def foo(self):
> > ... self.goo()
> > ...
> >>>> class B(A):
> > ... def goo(self):
> > ... print(1)
> > ...
> >
> > (2)
> >>>> class A:
> > ... def foo(self):
> > ... self.goo()
> > ... def goo(self): pass
> > ...
> >>>> class B(A):
> > ... def goo(self):
> > ... print(1)
> > ...
> >
> > Both can get the same result:
> >>>> b = B()
> >>>> b.foo()
> > 1
> >>>>
> >
> > What's the benefit of having the hook method goo() in class A in example 2?
> >
> > --Jach
> >
> None - as long as nobody tries one of those:
>
> a = A()
> a.foo()
>
> or
>
> class C(A):
> def foo(self):
> super().foo()
> print(2)
>
> c = C()
> c.foo()
Yes, there will be an attribute error if no goo() was defined.
What puzzles me is how a parent's method foo() can find its child's method goo(), no matter it was overwrote or not? MRO won't explain this and I can't find document about it also:-(
--Jach
More information about the Python-list
mailing list