Python Static and Class Methods

Last modified: 
Friday, May 1st, 2015
Topics: 
Python

Notes on creating static and class methods in Python using decorators.

class Boomba:

  def Roombie(self):
    """
    I am a regular method. If you try to call me unbound, I'll throw a fit.
    
    """
    s = 'Roombie'
    self.printMessage(s)

  @staticmethod
  def Bimba(): 
    """ 
    I am a static method. You can call me bound or unbound. I'm cool with it.
    Note that I have no self argument. My staticness is achieved by 
    using the with @staticmethod decorator.
 
    """ 
    s = 'Bimba'
    """
    printMessage() is called as a static method because Bimba() is a static method.
    This means there no self object to refer to when calling self.printMessage().
    """
    Boomba.printMessage(s)
    
  @classmethod
  def printMessage(cls, s):
    """
    I am class method. I may only be accessed within this class or instances thereof.
    """
    print 'Boomba %s## !' % s   

# Both bound methods behave normally.
b = Boomba()
b.Bimba()
b.Roombie()

# Fails with the following error:
# TypeError: unbound method Roombie() must be called with Boomba instance as 
# first argument (got nothing instead)
# Boomba.Roombie()

# But this static method totally works fine.
Boomba.Bimba()

# Class methods can be called as static methods...
s = 'Patoo'
Boomba.printMessage(s)

# ...or as bound methods.
s = 'Hibbity'
b.printMessage(s)


class Ipso(Boomba):
  """
  I works fine, which makes a person wonder about Python's implementation
  of class methods. I seem more protected than private.
  """
  def Odd(self):
    s = 'Faloon'
    self.printMessage(s)
    

ips = Ipso()
ips.Odd()


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.