Archive - Originally posted on "The Horse's Mouth" - 2010-02-01 22:31:24 - Graham Ellis
Most methods in classes that your write will be run on / applied to individual objects within that class - you'll be asking for the colour of a marker pen, or setting the price of a hotel room. You will NOT - typically - have a model in which all marker pens share the same colour.
But - just occasionally - you need a method that applies to the class as a whole, and this is known as a class (or static) method, and there are various ways of specifying such methods in your code.
In Java, for example, you can simply declare a method to be static (and you are then limited within the code of the method to only handling static variables in the class, as the method hasn't been run on any particular instance of the object).
In Python (from release 2.4), you can use an @staticmethod decorator before you declare your method that's to be static - see this example. You can also - in all versions - use something like counter = classmethod(getcount), and again we have a full example on the web site here
In Ruby, you declare the method name with a leading self. in front of the method name - so you declare def getnt()
rather than def self.getnt()
You can also use the class name in front of the method name - I show the alternative syntax in a full example [here]
but I'm going to discourage that - for if you rename the class, you really don't want to have to start messing about and renaming methods within the class as well!