1

I am trying to create a class derived from list so that it can have size and some other functions with following code:

class Mylist(list):
    def size(self):
        return len(self)

I can add other function similar to above.

I can create Mylist object with following code:

ll = Mylist([1,2,3])

But how can I add code so that when I create an object with following code, I get Mylist object and not usual list object:

ll = [1,2,3]

I have not been able to figure out how to do this. Thanks for your help.

rnso
  • 23,686
  • 25
  • 112
  • 234
  • 3
    What you want isn't possible. Well, not unless you were prepared to start tinkering with the source code of the interpreter (written in C) and be prepared to compile your own interpreter or possibly list class (also written in C). List statements have their own special op codes in the interpreter. These bypass anything you might be able to achieve writing only pure python. – Dunes May 09 '19 at 06:53
  • I have been able to do this for this syntax `ll=list([1,2,3])` but not for `ll=[1,2,3]`. I'm not sure why though. – Albin Paul May 09 '19 at 06:57
  • How can `ll=list([1,2,3])` return `Mylist` object? This will form an interesting answer. – rnso May 09 '19 at 06:59
  • You can always do `list = Mylist` as long as you know what you are doing. – Nishant May 09 '19 at 07:04
  • 2
    I got the feeling you might be going for something like this, given how hard the code in your previous question screamed "I miss Java" (or "I miss some language that looks kind of like Java"). You'll write much better code if you get used to how to code effectively in Python instead of trying to turn it into some other language you're more familiar with. – user2357112 May 09 '19 at 07:04
  • @Nishant With `list=Mylist` : Will that not create a circular inheritance: parent of `Mylist` will be `list` which is `Mylist` itself! – rnso May 09 '19 at 07:05
  • 1
    @mso no, that simply re-assign's names. There is no inheritance involved – juanpa.arrivillaga May 09 '19 at 07:06
  • @user2357112 : Haha. You are right. Its Java. – rnso May 09 '19 at 07:08

0 Answers0