I would like to change the behavior of the Python list display so that instead of creating listit, they create a subclass listthat I wrote. (Note: I do not think this is a good idea, I do it for fun, not for actual use.)
Here is what I did:
old_list = list
class CallableList(old_list):
def __init__(self, *args):
old_list.__init__(self)
for arg in args:
self.append(arg)
def __call__(self, start, end=None):
if end:
return self[start:end]
return self[start]
list = CallableList
After that, it returns the third element of the list:
x = list(1, 2, 3)
print x(2)
but it still gives an error:
x = [1, 2, 3]
print x(2)
The error is pretty simple:
Traceback (most recent call last):
File "list_test.py", line 23, in <module>
print x(2)
TypeError: 'list' object is not callable
I think that maybe there is no way to do this, but I can’t find anything that says so definitively. Any ideas?
source
share