1

I want to implement a class inherit from built-in class list and override a method, when I get an instance of this class, I can return a custom data, is it possible?

class MyList(list):
    def the_method(self):
        # do some thing
        return [1, 2]

inst = MyList()
print inst # [1, 2]

Usually when I print an instance of class I will get 'xxx object at 0x0000000002D92358', but if I print an instance of class which inherit from list, I will get a list output, how python do that?

nopa
  • 11
  • 1
  • 3

2 Answers2

1

You'll need to teach python how to convert your class into a string.

Python's base object has two methods which handle conversion into a string: __repr__ and __str__. In order to get the result you want, you'll need to override them.

These two functions serve a similar but not identical purpose. You can find out what the exact difference between them is here. A nice explanation given by Ned Batchelder is:

My rule of thumb: __repr__ is for developers, __str__ is for customers.

In your case however, you don't need to make them different. The unambiguous representation of your custom list class is also the most readable, therefore the two functions can return the same result.

Modify your class like so:

class MyList(list):
    def __repr__(self):
        return str([1,2])
    def __str__(self):
        return self.__repr__()

Note that both functions have to return a string, hence the call to str in the return statement of __repr__.

stelioslogothetis
  • 9,371
  • 3
  • 28
  • 53
  • But I also want to get a custom list(realt-ime from database) when I try reach the variable mylist (mylist = MyList()), can I do it? – nopa Aug 15 '17 at 02:22
  • @nopa You asked about getting the string representation. What you're asking about now is completely unrelated. You should accept an answer to this question and then ask a new one, with a clear description of your new issue. Then, somebody who has the required knowledge will help you. – stelioslogothetis Aug 15 '17 at 10:09
  • Maybe I have not make sure what design I really need, no matter how, thanks for reply – nopa Aug 16 '17 at 02:26
0

You can modify the representation of an object if you override __repr__(self) method. But it has to return str type.

>>> class MyList(list):
    def do(self):
        return [1, 2]
    def __repr__(self):
        return '[1, 2]'


>>> inst = MyList()
>>> inst
[1, 2]

About the difference between __repr__ and __str__, there is a great explanation here https://stackoverflow.com/a/2626364/840582

Chen A.
  • 10,140
  • 3
  • 42
  • 61
  • But I also want to get a custom list(realt-ime from database) when I try reach the variable mylist (mylist = MyList()), can I do it? – nopa Aug 15 '17 at 02:23
  • Sounds like you'll need to define a class with a list object, not extending it – Chen A. Aug 15 '17 at 06:55