If I have a class named Foo
, then normally a call using syntax Foo()
constructs a new instance and initializes it using the __init__
(method/function). I would like a slightly different (optimized) behavior. I would like to memoize the instances according to the arguments of Foo(...)
and if ever the same arguments are given, then return the same/identical instance as before, otherwise continue with the default construction protocol. I'll need of course to somewhere implement a cache to memoize the object. I could put that cache in a global variable or even in a property on the class itself.
But does the Python object system allow me to do this?
As I understand __init__
CANNOT be used for this purpose as its return value is ignored by the system.
Of course, one way of course is to never call Foo()
directly in my code, but always call makeFoo
, but please note that that is not my question. This would be pretty awkward because my program has a hierarchy of such classes, only some of which are memorable. I don't want to make this different visible to the application programmer.