There has been a discussion in chat relating to a question (the question itself being irrelevant to this one), that has revealed I may not know Python whatsoever.
In my mind, although terminology differs across languages, we may generally categorise functions as:
- [free] functions
- static methods / static member functions
- non-static methods / non-static member functions
Apparently in Python there is another kind of function that doesn't fit into the above categories, one that is a method but "doesn't know its class".
What are "class methods" and "instance methods", in Python?
Best Answer
The short answer
The long answer
Class methods
A class method is one that belongs to the class as a whole. It doesn't require an instance. Instead, the class will automatically be sent as the first argument. A class method is declared with the
@classmethod
decorator.For example:
Instance Methods
On the other hand, an instance method requires an instance in order to call it, and requires no decorator. This is by far the most common type of method.
(note: the above is with python3; with python2 you'll get a slightly different error)
Static methods
A static method is similar to a class method, but won't get the class object as an automatic parameter. It is created by using the
@staticmethod
decorator.Documentation links
Here are links to the relevant python3 documentaton:
The data model documentation has this to say about the difference between class methods and static methods:
Related questions