How to define Static Methods and Class Methods

Get to know Static Methods and Class Methods

Static methods and class methods are created by wrapping methods in objects of the staticmethod and classmethod types, respectively.

Static methods are defined without self arguments, and can be called directly on the class itself.

Class methods are defined with a self-like parameter normally called cls. You can call class methods directly on the class object too, and the cls parameter then automatically is bound to the class.


__metaclass__ = type #   w  w w  . j a v  a  2  s .c o m

class MyClass: 

    def smeth(): 
        print 'This is a static method' 
    smeth = staticmethod(smeth) 

    def cmeth(cls): 
        print 'This is a class method of', cls 
    cmeth = classmethod(cmeth) 
MyClass.smeth() 
MyClass.cmeth() 

The code above generates the following result.

We can also use decorators to define static methods and class methods.


__metaclass__ = type #  w  ww . j a  va 2s  .  c  o  m

class MyClass: 
   @staticmethod 
   def smeth(): 
       print 'This is a static method' 

   @classmethod 
   def cmeth(cls): 
       print 'This is a class method of', cls 

MyClass.smeth() 
MyClass.cmeth() 

The code above generates the following result.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules