Python 3K or Python 2.9?
aleax at mac.com
Thu Sep 13 17:23:07 CEST 2007
TheFlyingDutchman <zzbbaadd at aol.com> wrote:
> > >>> Foo.bar(foo, "spam")
> > >>> foo.bar("spam")
> That looks like a case of "There's more than one way to do it". ;)
> The first form is definitely consistent with the
> method declaration, so there's a lot to be said for using that style
> when teaching people to make classes -> send self, receive self.
On the other hand, the second form is not polymorphic: it doesn't allow
for foo to be an instance of some OTHER class (possibly subclassing Foo
and overriding bar) -- it will call the Foo version of bar anyway.
type(foo).bar(foo, "spam") *IS* almost semantically equivalent to the
obviousy simpler foo.bar("spam") -- but doesn't cover the possibility
for foo to do a *per-instance* override of 'bar'.
getattr(foo, 'bar', functools.partial(type(foo).bar, foo))("spam") is
getting closer to full semantic equivalence. And if you think that's
"another OBVIOUS way of doing it" wrt foo.bar("spam"), I think your
definition of "obvious" may need a reset (not to mention the fact that
the "equivalent" version is way slower;-).
Foo.bar(foo, "spam")'s different semantics are important when any
implementation of type(foo).bar (or other method yet) wants to BYPASS
polymorphism to redirect part of the functionality to a specific type's
implementation of bar ('super' may help in some cases, but it keeps some
polymorphic aspects and pretty often you just want to cut all
polymorphism off and just redirect to ONE specific implementation).
More information about the Python-list