Interview and often ask to staticmethod classmethod What is the difference?
First, look at the official explanation:
staticmethod:
class staticmethod
staticmethod(function) -> method
Convert a function to be a static method.
A static method does not receive an implicit first argument. To declare a static method, use this idiom:
class C:
def f(arg1, arg2, ...): ...
f = staticmethod(f)It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class.
Static methods in Python are similar to those found in Java or C++. For a more advanced concept,
Its role is to be a function of a class into a static function. Static function and role of java, c ++ static function similar to the role of some global variables.
classmethod:
class classmethod
classmethod(function) -> method
Convert a function to be a class method.
A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:
class C: def f(cls, arg1, arg2, ...): ... f = classmethod(f)
It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.
Class methods are different than C++ or Java static methods. If you want those, see the staticmethod builtin.
classmethod and c ++, java methods of different classes. Parameter class is a class method, examples of the method parameter is an example.
For example, the following program:
class A: @staticmethod def a(): print "this is a" @classmethod def b(rty): print(rty) print "this is b" testa = A() testa.a() testa.b() # 输出为: # this is a # __main__.A # this is b
Which __main __. A name A class of.
If @classmethod removed, the result is output:
class A: @staticmethod def a(): print "this is a" # @classmethod def b(rty): print(rty) print "this is b" testa = A() testa.a() testa.b() # 输出为: # this is a # <__main__.A instance at 0x1070f03f8> # this is b
We can see this time rty content, for instance of the class A address. C ++ class methods, and it's not the same child, class methods c ++, java must be invoked by example.