An alternative approach to bound methods

Marcin 'Qrczak' Kowalczyk qrczak at knm.org.pl
Sat Feb 24 09:03:18 EST 2001


Fri, 23 Feb 2001 12:33:00 +0100, Alex Martelli <aleaxit at yahoo.com> pisze:

> class Aclass:
>     def amethod(x, *args):
>         # body snipped
> 
> is this 'amethod' a "class method" or an "instance method"?

Both.

> Does calling it via
> 
>     x=Aclass();x.amethod(y,z)
> 
> or via
> 
>     x=Aclass();Aclass.amethod(x,y,z)
> 
> change anything?

No.

> > Are you asking about the semantics of a particular piece of code?
> > If so, which code? My proposal is unambiguous.
> 
> And it does unambiguously mean that mentioning 'amethod' within
> the above amethod's code body will in fact refer to Aclass.amethod,
> not self.amethod, then?

Yes.

> People will often and erroneously make recursive calls to
> "amethod(a,b,c)" when they should be going through self, because
> "going through self" IS the normal, most frequently desired case.

Both are equally easy. Why would anybody write
    amethod(self,b,c)
instead of
    self.amethod(b,c)
when he means the latter?

> And this is checked at runtime, and gives a very clear
> error message if the user makes a mistake about it:
> 
> TypeError: unbound method must be called with class instance 1st argument

It's not necessarily a mistake.

> class Derived(Base):
>     def foo(self, *args):
>         print "Derived.foo",args
>         Base.foo(*args)
> 
> I don't want this error to become a silent, mysterious one; we know
> have clear diagnostics for it, and losing them would be a serious
> step backwards.

I admit that this error would have a worse diagnostics (usually:
too few arguments, i.e. not that bad). The same can be said about
writing 'self' in method definitions: when one forgets it, the error
is equally mysterious.

-- 
 __("<  Marcin Kowalczyk * qrczak at knm.org.pl http://qrczak.ids.net.pl/
 \__/
  ^^                      SYGNATURA ZASTĘPCZA
QRCZAK



More information about the Python-list mailing list