What are “class methods” and “instance methods”, in Python?
Remember math class, "y is a function of x, f(x)
?" Keep that in mind as you read the following descriptions:
Instance Methods
An instance method is function that is a function of an instance. It accepts the instance as an argument to it.
A built-in example of an instance method is str.lower:
>>> 'ABC'.lower()
'abc'
called on the instance of the string, it uses that information to return a new string.
Class Methods:
Remember, in Python, everything is an object. That means the class is an object, and can be passed as an argument to a function.
A class method is a function that is a function of the class. It accepts the class as an argument to it.
A builtin example is dict.fromkeys
:
>>> dict.fromkeys('ABC')
{'C': None, 'B': None, 'A': None}
It implicitly knows its own class, and creates a new one of that class from the iterable. An OrderedDict demonstrates this when using the same method:
>>> from collections import OrderedDict
>>> OrderedDict.fromkeys('ABC')
OrderedDict([('A', None), ('B', None), ('C', None)])
Static Methods
You mention a method that "doesn't know its class" - this is a static method in Python. It is merely attached for convenience to the class object. It could optionally be a separate function in another module, but its call signature would be the same.
A static method is a function of neither the class nor the object.
A built-in example of a static method is str.maketrans from Python 3.
>>> str.maketrans('abc', 'bca')
{97: 98, 98: 99, 99: 97}
Given a couple of arguments, it makes a dictionary that is not a function of its class.
It is convenient because str
is always available in the global namespace, so you can easily use it with the translate function:
>>> 'abracadabra'.translate(str.maketrans('abc', 'bca'))
'bcrbabdbcrb'
In Python 2, you have to access it from the string
module:
>>> 'abracadabra'.translate(str.maketrans('abc', 'bca'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'str' has no attribute 'maketrans'
>>> import string
>>> 'abracadabra'.translate(string.maketrans('abc', 'bca'))
'bcrbabdbcrb'
Example
class AClass(object):
"""In Python, a class may have several types of methods:
instance methods, class methods, and static methods
"""
def an_instance_method(self, x, y, z=None):
"""this is a function of the instance of the object
self is the object's instance
"""
return self.a_class_method(x, y)
@classmethod
def a_class_method(cls, x, y, z=None):
"""this is a function of the class of the object
cls is the object's class
"""
return cls.a_static_method(x, y, z=z)
@staticmethod
def a_static_method(x, y, z=None):
"""this is neither a function of the instance or class to
which it is attached
"""
return x, y, z
Let's instantiate:
>>> instance = AClass()
Now the instance can call all of the methods:
>>> instance.an_instance_method('x', 'y')
('x', 'y', None)
>>> instance.a_static_method('x', 'y')
('x', 'y', None)
>>> instance.a_class_method('x', 'y')
('x', 'y', None)
But the class is not usually intended to call the instance method, though it is expected to call the others:
>>> AClass.a_class_method('x', 'y')
('x', 'y', None)
>>> AClass.a_static_method('x', 'y')
('x', 'y', None)
>>> AClass.an_instance_method('x', 'y')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an_instance_method() missing 1 required positional argument: 'y'
You would have to explicitly pass the instance to call the instance method:
>>> AClass.an_instance_method(instance, 'x', 'y')
('x', 'y', None)