How can I remove the __size attribute in this object ?
class Object():
def __init__(self, size):
self.__size = size
def __len__(self):
return self.__size
How can the init function create the len function ? Lambda function ?
PS: In my real case, I have some calculations to do in this len function, but after instantiation the result is always the same (like a tuple for instance). It might be great to save this result in a function without any hidden attribute.
I would not recommend this, but you can use a simple lambda function
The reasons why I would not recommend this are subsummed in the Zen of Python: Explicit is better than implicit. Simple is better than complex.
If you are using an instance variable, then it is explicit, you have better stacktraces for errors, you can use doctests in you
__len__function and the code is easier to understand when reading and updating it.