Is it possible to dynamically assign special methods, such as __getitem__
, to an instance of a class using setattr()
? For example, if I have this:
class Example (object): pass
And then try the following:
>>> example = Example() >>> setattr(example, '__getitem__', lambda x: 1)
I get this:
>>> example['something'] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'Example' object has no attribute '__getitem__'
But of course, this works great:
>>> example.__getitem__('something') 1
Obviously, something is happening here that I donβt understand how Python performs method searches for this kind of thing. Should these methods be installed in the class and not on the instance?
UPDATE
So, I have to clearly clarify how I know that I see this in the Example
class ... I was hoping there was a way to set them for each instance, but the consensus that I see so far, you cannot do this.
source share