How to store functions as class variables in python?
You are storing an unbound built-in method on your class, meaning it is a descriptor object. When you then try to access that on self
, descriptor binding applies but the __get__
method called to complete the binding tells you that it can't be bound to your custom class instances, because the method would only work on str
instances. That's a strict limitation of most methods of built-in types.
You need to store it in a different manner; putting it inside another container, such as a list or dictionary, would avoid binding. Or you could wrap it in a staticmethod
descriptor to have it be bound and return the original. Another option is to not store this as a class attribute, and simply create an instance attribute in __init__
.
But in this case, I'd not store str.lower
as an attribute value, at all. I'd store None
and fall back to str.lower
when you still encounter None
:
return data.rename(columns=self.my_func_mask or str.lower)
Setting my_func_mask
to None
is a better indicator that a default is going to be used, clearly distinguishable from explicitly setting str.lower
as the mask.