overriding methods - two questions

davisn90210 at gmail.com davisn90210 at gmail.com
Fri Nov 16 21:29:09 CET 2007


On Nov 16, 11:35 am, Donn Ingle <donn.in... at gmail.com> wrote:
> >This may help (on an old Python version):
> >>>> class Sam: pass
> >>>> class Judy:
> > ...    def foo(self): pass
> > ...
> >>>> children = [Sam(), Judy(), Sam()]
> >>>> for child in children: hasattr(child, "foo")
> > ...
> > False
> > True
> > False
>
> That's not what my tests are showing. While Sam has no foo, it's coming from
> (in my OP) Child (which is the parent class), so hasattr(Sam(),"foo") is
> returning True.
>
> /d

But also in your OP: "I want to run the foo() method for each one that
*has* a foo() method ...."  So hasattr(child, "foo") really does
answer the question as posed, even if it's not really what you want.
I am curious as to why you want to go through such contortions.  What
do you gain.  What happens, for example, if a subclass of Judy is
passed in that does not override foo?  Should foo be called in that
case or not?

--Nathan Davis



More information about the Python-list mailing list