staticidentifier used in a
Classmethod 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
class methodare different. Take the following Python code as example:
class_number = 100
self.number = 0
print "instance method", arg
print "class method", arg
print "static method", arg
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
selfis instance argument. By passing instance itself to a instance method, other instance methods or instance variables, such as
self.number, are accessible.
@classmethodis 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
@staticmethodis 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.