Is it possible to redefine which object the brackets [] use?
I can subclass the list object, but how to I make the interpreter use my subclass in place of the buildin list object? Is it possible?
(I’m pretty sure I’m using the wrong terms for the question- feel free to edit)
>>> class mlist(list):
... def __init__(self):
... list.__init__(self)
... def __getitem__(self, item):
... return list.__getitem__(self, item) * 2
...
>>> testlist = mlist()
>>> testlist.append(21)
>>> testlist[0]
42
>>> list = mlist() # maybe setting the 'list' type will do it?
>>> testlist = []
>>> testlist.append(21)
>>> testlist[0]
21 # Nope
>>>
I don’t have a practical use for this- just curious.
Try running the code after you’ve run the code you posted
Now, determine the type using the code I’ve posted
it seems that
[]createslist, instead ofmlist, it looks strange :SUpdate
I checked the bytecode generated using
dis, and the code below was generatedIt appears that
listwill invoke whatever is assigned to it, while[]will be converted toBUILD_LISTbytecode. It appears that[]is not translated tolist, hence[]‘s behavior is stucked to creating list.Update 2
Python class can be updated
Well, except for builtin classes, like list