dundermethods are only looked up on the class, so assigning it to f has no effect. You’d have to overwrite the definition of Foo.__setattr__ for it to work