Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Static methods A static method is a method that you can call on a class, or on any instance of the class, without the special behavior and constraints of ordinary methods, bound and unbound, on the first argument. A static method may have any signature: it may have no arguments, and the first argument, if any, plays no special role. You can think of a static method as an ordinary function that you're able to call normally, despite the fact that it happens to be bound to a class attribute. While it is never necessary to define static methods (you could always define a function instead), some programmers consider them to be an elegant alternative to such functions whose purpose is tightly bound to some specific class. You build a static method by calling built-in type staticmethod and binding its result to a class attribute. Like all binding of class attributes, this is normally done in the body of the class, but you may also choose to perform it elsewhere. The only argu- ment to staticmethod is the function to invoke when Python calls the static method. The following example shows how to define and call a static method: class AClass(object): def astatic( ): print 'a static method' astatic = staticmethod(astatic) anInstance = AClass( ) AClass.astatic( ) # prints: a static method anInstance.astatic( ) # prints: a static method This example uses the same name for the function passed to staticmethod and for the attribute bound to staticmethod 's result. This style is not mandatory, but it's a