What is the difference between a function decorated with @staticmethod
and one decorated with @classmethod
?
source: stackoverflow
author: Daryl Spitzer
Sign Up to our social questions and Answers to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers to ask questions, answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Maybe a bit of example code will help: Notice the difference in the call signatures of
foo
,class_foo
andstatic_foo
:Below is the usual way an object instance calls a method. The object instance,
a
, is implicitly passed as the first argument.With classmethods, the class of the object instance is implicitly passed as the first argument instead of
self
.You can also call
class_foo
using the class. In fact, if you define something to be a classmethod, it is probably because you intend to call it from the class rather than from a class instance.A.foo(1)
would have raised a TypeError, butA.class_foo(1)
works just fine:One use people have found for class methods is to create inheritable alternative constructors.
With staticmethods, neither
self
(the object instance) norcls
(the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class:Staticmethods are used to group functions which have some logical connection with a class to the class.
foo
is just a function, but when you calla.foo
you don’t just get the function, you get a “partially applied” version of the function with the object instancea
bound as the first argument to the function.foo
expects 2 arguments, whilea.foo
only expects 1 argument.a
is bound tofoo
. That is what is meant by the term “bound” below:With
a.class_foo
,a
is not bound toclass_foo
, rather the classA
is bound toclass_foo
.Here, with a staticmethod, even though it is a method,
a.static_foo
just returns a good ‘ole function with no arguments bound.static_foo
expects 1 argument, anda.static_foo
expects 1 argument too.And of course the same thing happens when you call
static_foo
with the classA
instead.source: stackoverflow
author: unutbu