for the purposes of a completely contrived programming exercise, I want to be able to access all objects that I have created of a specific class, using decorators, and by subscripting the class itself.
In the below example, I have created an instance of my A class, using the argument 1, and stored the result in a dictionary, using the key '1'.
So, by attempting to index the A class directly, it should return the instance of the object that was created, however, it only returns the parameter passed to __get__item, and raises a TypeError if I attempt to index it directly with A['1'].
import types
def remember(cl):
seen = dict()
def _remember(*args, **kwargs):
key = ','.join(map(str, args))
if key not in seen:
seen[key] = cl(*args, **kwargs)
return seen[key]
_remember.__getitem__ = types.MethodType(seen.get, _remember)
return _remember
@remember
class A(object):
def __init__(self, x):
pass
a = A(1)
b = A.__getitem__('1')
print(a == b) #should print true, but instead, A.__get__item returns '1'. Ideally, A['1'] would work.