Methods that run on classes (static methods) in Python
Archive - Originally posted on "The Horse's Mouth" - 2010-03-25 07:16:53 - Graham Ellis
• If you want to write a class or static method in Python, you can write an object (or dynamic) method and then call the classmethod function to make it into a method that can additionally run on the the class as a whole:
def counter(cls):
# This is a 'dynamic' method
return thing.count
# Which we'll wrap to make (in effect) static too.
ctr = classmethod(counter)
Note that the method takes an object parameter (which we have chosen to label "cls" rather than "self") but it hasn't been used in the code block.
• In more recent versions of Python, you can also use a decorator to achieve the same thing - in fact, it's just a change of the syntax and does the same thing underneath - a decorator is a wrapper:
@classmethod
def counter2(self):
# "self" is the object or the class
return thing.count
• You can also use a staticmethod decorator to define a static method - but in this case the static behavior replaces the object or dynamic behavior rather than being additional, and so you don't pass in an object reference:
@staticmethod
def counter():
return thing.count
There are working examples of each of these in the source code which is [here], written on yesterday's public python class where I was teaching Python Programming.