Magic attributes

Python objects can have special attribute names for easy operator overloading.


class StatefulFunction:
    def __init__(self, state=0):
        self.state = state
        
    def __call__(self, x):
        self.state += x
        return self.state

    def __add__(self, x):
        return self.state + x

f = StatefulFunction(3)
f(2)  # 5
f(2)  # 7
f + 3 # 10, f.state is unchanged.

There are better ways of acheiving this particular example.