[Tutor] what is @classmethod and @staticmethod ??

Alan Gauld alan.gauld at btinternet.com
Sat Mar 22 15:07:11 CET 2008

"maser" <maseriyer at yahoo.com> wrote

> I couldn't find a good resource explaining what
> @classmethod and @staticmethod are in python and when,
> how these could be used.

I'm not sure which aspect of this is the problem
Andreas has explained the strange @ syntax for a decorator
however if its the concepts of class method and static method
that confuss then that probably didn't help :-)

So first I ask do you know what a class method  (or static method)
is? (Unless you are a language lawyer you can almost consider
them as synonyms). If not the simple answer is that a class
method is one which acts on the class itself rather than on
instances of the class (I'll assume you understand the difference
between classes and instances (or objects)). This if you have a
Circle class for example there might be a class method to return
the count of how many Circle instances exist. It might look like this:

class Circle(object):
    count = 0    # a class variable
    def __init__(self, radius=10):
        Circle.count += 1
        self.radius = radius
    def __del__(self):
        Circle.count -= 1

    def circles(this):
        return Circle.count

c1 = Circle()
c2 = Circle(5)
c3 = Circle(42)
print Circle.circles()

Does that help?

Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list