@classmethod and @staticmethod in Python

In C++ or Java, the static identifier used in a Class method is to declare the function to be bound to that Class. This are also known as class methods and you could use them in class level without initiating an instance first. In Python, however, the ideas of static method and class method are different. Take the following Python code as example:

class MethodDemo(object):
    class_number = 100

    def __init__(self):
        self.number = 0

    def Show(*arg):
        print "instance method", arg

    def ClassShow(*arg):
        print "class method", arg

    def StaticShow(*arg):
        print "static method", arg

def main():
    d = MethodDemo()
    d.ClassShow()  # same as MethodDemo.ClassShow()
    d.StaticShow() # same as MethodDemo.StaticShow()

if __name__ == '__main__':

And the result on my computer is:

instance method (<__main__.MethodDemo instance at 0x10cef93f8>,)
class method (<class __main__.MethodDemo at 0x10ceb3ae0>,)
static method ()

The first argument in instance method Show() is the instance object of that class (bound to instance). Usually this kind of method is defined as "def Show(self):", and self is instance argument. By passing instance itself to a instance method, other instance methods or instance variables, such as self.number, are accessible.

If decorator @classmethod is used to define a method then that method is a class method. From above code snippet, the first argument to be passed into a class method is the class object (bound to class). As a result, from a class method, you could access other class methods or class variables, such as class_number.

If decorator @staticmethod is used to define a method then that method is a static method. There is no arguments to be passed into a static method by default (bound to nothing). It is like a normal function outside a class in global scope. The usage of static methods are like global functions and the class name will be namespace to solve the conflict of same function names in global scope.

No comments: