Welcome, guest | Sign In | My Account | Store | Cart

In order to change into a list, the length of an instance is investigated first. "__len__()" Next, all the contents are taken out in order. "__getitem__()"

Python, 11 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Listlike:
    def __init__(self):
        self.list = [1, 2, 3, 4, 5]
    def __getitem__(self, index):
        return self.list[index]
    def __len__(self):
        return len(self.list)

>>> listlike = Listlike()
>>> list(listlike)
[1, 2, 3, 4, 5]

Intrinsic function list() list-izes the character sequence and tuple other than an instance like the point. Besides calling list(), it can take out by tuple() or for loop, or map()/reduce()/filter() can be used.

1 comment

Alexander Semenov 21 years, 7 months ago  # | flag

No need for __len__ here.

Created by Keisuke URAGO on Thu, 5 Sep 2002 (PSF)
Python recipes (4591)
Keisuke URAGO's recipes (12)

Required Modules

  • (none specified)

Other Information and Tasks