Creating Static Methods in Python

This is a short introductory guide to creating static methods. Static methods, though not used entirely that often, can be a very useful tool. I personally get the most use out of them when organizing my code.

Python’s static methods have a similar implementation as Java & C++. Static methods were not introduced into Python until version 2.2

Example of version 2.2 and higher implementation:


>>> class Foo:
...     def bar(arg):
...         Foo.arg = arg
...     bar = staticmethod(bar)
...
>>> Foo.bar('Hello World')
>>> Foo.arg
'Hello World'
>>> Foo().bar('Hello')
>>> Foo.arg
'Hello'

Static methods can be called either on the class (such as Foo.bar()) or on an instance (such as Foo().bar()). The instance is ignored except for its class.

In version 2.4, function decorator syntax was added, which allows another way to define a static method. If you are using 2.4 or above, this is the recommended way of creating a static method.

Example of version 2.4 and higher implementation:


>>> class Foo:
...     @staticmethod
...     def bar(arg):
...         Foo.arg = arg
...
>>> Foo.bar('Hello World')
>>> Foo.arg
'Hello World'
>>> Foo().bar('Hello')
>>> Foo.arg
'Hello'

If you are looking to do more advanced static methods, look into using classmethod instead of staticmethod. One of the differences between the two is that class method receives the class as implicit first argument, just like an instance method receives the instance. For further reading on class method, refer to the built in functions page. If anyone is interested in seeing example of class method in use, let me know.

2 Responses to “Creating Static Methods in Python”

  • peter tomovascitch

    thx. nice review. i’d like to see some class method examples, if you got them. i also got a rather ignorant question: under what circumstances do you not want to bind a function to a class. i’ve been trying to correlated that to c++ but coming up short, mentally, that is; especially, if you have a class that has bound methods in it. cheers.

  • @peter: Thanks for the comment!

    Usually, static methods would be used for Singleton or Factory Patterns (http://en.wikipedia.org/wiki/Factory_method_pattern), but if you review this page, you will see Python doesn’t require a static method to be used to implement the Factory pattern.

    Coming up with an example for static methods can be difficult. I usually use static methods in python for organization purposes. For instance, if I made a DB abstraction layer and had a few functions that were related to the DB layer, but weren’t necessary used in the class, I would added them as static methods. Keeps those functions organized in once place, plus I find it easier to remember.

    For example:

    >>> data = db_convertAsciiToHtml(”Foo & Bar”)

    OR

    >>> data = DB.convertAsciiToHtml(”Foo & Bar”)

Trackbacks

  •