Static Methods
Date: February 18th 2016
Last updated: February 18th 2016
Static methods are special methods that don't depend on the object itself. Importantly, static methods don't have access to attributes of a class or an instance of a class. You can use a static method if you want to use the method without instantiating the class.
#!/usr/bin/python2
class Foo(object):
def __init__(self, x):
self.x = x
def metA(self):
print "method A = {}".format(self.x)
@staticmethod
def metB(y): #<====== no access to self.x or self.metA()
evens = 'yes' if y % 2 == 0 else 'no' #<===== Ternary operator
print "static method B"
print "Number is even: {}".format(evens)
# Decoration is the same using staticmethod after the function has been made...
# metB = staticmethod(metB)
Normal execution of the class:
Method A (normal class method) is ONLY callable after instantiating the class.
Foo.metA
# <unbound method Foo.metA>
Foo.metA()
# TypeError: unbound method metA() must be called with
# Foo instance as first argument (got nothing instead)
f = Foo(10)
f.x
# 10
f.metA
# <bound method Foo.metA of ... >
f.metA()
# method A = 10
Staticmethod:
Method B is callable with or without instantiating the class
Foo.metB #note this is a FUNCTION not an unbound method
# <function metB at 0x7fbd69d53de8>
Foo.metB(1)
# static method B
# Number is even: no
# instantiate the class
f=Foo(5)
f.x
# 5
f.metB(10)
# static method B
# Number is even: yes
Pros
- No self argument is passed
- Reduces memory usage (doesn't call a bound method)
- Improves code readability
Useful resources: