Python developers can customize how code is interpreted by defining special methods (also called magic methods). For example, it is possible to
override how the multiplication operator (a * b
) will apply to instances of a class by defining in this class the __mul__
and __rmul__
methods. Whenever a multiplication operation is performed with this class, the python interpreter will call one of these
methods instead of performing the default multiplication.
The python interpreter will always call these methods with the same number of parameters. Every call to a special method will fail if it is defined
with an unexpected number of parameters.
This rule raises an issue when a special method is defined with an unexpected number of parameters.
Noncompliant Code Example
class A:
def __mul__(self, other, unexpected): # Noncompliant. Too many parameters
return 42
def __add__(self): # Noncompliant. Missing one parameter
return 42
A() * 3 # TypeError: __mul__() missing 1 required positional argument: 'unexpected'
A() + 3 # TypeError: __add__() takes 1 positional argument but 2 were given
Compliant Solution
class A:
def __mul__(self, other):
return 42
def __add__(self, other):
return 42
A() * 3
A() + 3
See