The difference comes mainly when subclassing. You can think of a staticmethod as just a function definition inside a class. It has no self argument, so it basically ignores the class it is defined in. It is just like having the function outside the class. It's use is to put it closer to the code that uses it for stylistic reasons.
A classmethod on the other hand does have self. So you should use this if the class is important. Remember that in Python self always refers to the class the method is being called on. So if you have class A with a classmethod and subclass B of A, and you call the classmethod on B, then self will refer to B. A classmethod is usually used for alternate initializers, one of the prime examples of something you want to call on a class, not an instance. Aaron Meurer On Aug 28, 2012, at 10:17 AM, Tom Bachmann <[email protected]> wrote: > I'm afraid I cannot find anything real either, so maybe it's not really true. > I remember this from a talk by guido I watched a while ago. > > Some vague support of my memory: > > http://mail.python.org/pipermail/tutor/2010-September/078542.html > > http://www.peterbe.com/plog/newfound-love-of-staticmethod [first comment] > > http://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python > > On 28.08.2012 14:27, Sergiu Ivanov wrote: >> Hello, >> >> While writing one of my classes, I needed to factor out some bits of >> functionality into private, instance-independent functions. To avoid >> supplying any extra arguments to these functions, I have made them >> into static methods using the @staticmethod decorator. >> >> However, Tom has pointed out [0] that @classmethod would be preferable >> instead. I have tried to google why that would be the case, but I >> haven't managed to dig anything out. Grepping over the source of >> SymPy reveals the usage of @staticmethod on occasions almost as >> numerous as those where @classmethod is used. >> >> Is there a fixed strategy when to use one of the two decorators in >> SymPy? >> >> Sergiu >> >> [0] >> https://github.com/scolobb/sympy/commit/603fd9e97f5b3215f3165f265a806b09fb80a830#sympy-categories-diagram_drawing-py-P6 >> > > -- > You received this message because you are subscribed to the Google Groups > "sympy" group. > To post to this group, send email to [email protected]. > To unsubscribe from this group, send email to > [email protected]. > For more options, visit this group at > http://groups.google.com/group/sympy?hl=en. > -- You received this message because you are subscribed to the Google Groups "sympy" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/sympy?hl=en.
