Python FAQ
Q: What do the __init__
, __call__
, and __hash__
functions do? (Magic Methods)
These methods are known as magic methods in Python, and they correspond to actions on classes that you define. You may be most familiar with the __init__
method (also known as the constructor), which is called when you create a new instance of the object. Consider the following minimal class example:
class TestClass:
def __init__(self, name: str) -> None:
self.name = name
instance = TestClass('Banana')
print(instance.name) # Prints 'Banana'
Similarly, the __call__
method defines what happens when an instance of the object is called like a function. A minimal example is as follows:
class TestClass:
def __call__(self, n: int) -> str:
"""
Returns the string "Ah!" but with `n` A's.
"""
return n * "A" + "h!"
instance = TestClass()
print(instance(8)) # Prints "AAAAAAAAh!"
The same is largely true for the __hash__
function, which just determines what hash(x)
returns on that class. For instance, if I write a class:
class TestClass:
def __hash__(self) -> str:
return 'Hi!'
t = TestClass()
hash(t) # Returns 'Hi!'
Meaning that calling hash(t)
is really just the same as calling t.__hash__()
.
We can also use magic methods to define what happens when we use operations on objects. For instance, we can override the default *
operator for multiplication using the __mult__
magic method, as follows:
class Integer:
def __init__(self, x: int) -> None:
self.x = x
def __mult__(self, y: int) -> Integer:
return Integer(self.x * y)
a = Integer(3)
b = Integer(5)
c = a * b # c = Integer(15)
print(c.x) # Prints '15'
You may see other magic methods (such as __rshift__
, __len__
, __rmod__
, etc) that correspond to other operations on objects. They generally work the same as the examples above, but for a more detailed guide you can check out the link here.