Can I override Python list display?

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?

+3
source share
3 answers

, , . .

+3

Python. , list-comprehensions, , , list, . , Python . , CPython, Objects/listobject.c.

+1
   >>> print(x(2)) # works in 2.7
   3
   >>> type(x)
   <class '__main__.CallableList'>
   >>> y = [1,2,3]
   >>> type(y)
   <type 'list'>

"", , list list list() CallableList. ,

   >>> fred = CallableList
   >>> type(fred)
   <type 'type'>
   >>> x = fred(1,2,3)
   >>> x
   [1, 2, 3]
   >>> print x(2)
   3
   >>> 
-1

Source: https://habr.com/ru/post/1766579/


All Articles