Why there is a parameter named "self" for classmethod function?

Aaron Brady castironpi at gmail.com
Thu May 7 07:27:15 EDT 2009


On May 7, 1:29 am, Steven D'Aprano
<ste... at REMOVE.THIS.cybersource.com.au> wrote:
> On Thu, 07 May 2009 00:39:28 -0400, Terry Reedy wrote:
> > Functions that refer to neither the class nor an instance thereof can
> > usually be moved outside the class altogether.  Python is not Java.  I
> > believe staticmethod() was mainly added because it is needed for
> > .__new__(), at least in some appearances.
>
> Can be, but if there's reason enough to keep it with a class, there's no
> reason not to. Sometimes I have a class with a few methods that share
> common code, but that code happens to not include self (or cls). Since
> the common code is only of interest to that class, even though it doesn't
> need the instance, I factor the common code out into a method.
>
> This would be a good candidate for a staticmethod, only due to laziness I
> don't usually bother :)
>
> --
> Steven

It's also useful if you want to access the function using the syntax
of attributes, as in 'self.amethod' where 'amethod' is a static
method.  If I understand correctly, no bound method is created if the
function is static, and as such, the decorator can increase
performance.

> Can be, but if there's reason enough to keep it with a class, there's no
> reason not to.

That's a bit of hyperbole; the usual reasons such as code bloat,
namespace bloat, maintainability etc. all weigh against it.  It's just
that the benefits weigh heavier.

There is something that is 'correct' about it IMO, that is, provides
syntax to what is valid semantics in an OO context.  That may just be
another way of stating the thesis though.



More information about the Python-list mailing list