rohithpr
rohithpr

Reputation: 6330

Is there a way to define list(obj) method on a user defined class in python?

One can can implement the method __str__(self) to return a string. Is there an __list__(self) counterpart? (__list__ doesn't work!) Is .toList() the way to go?


See also: Let a class behave like it's a list in Python if you don't actually need to convert to a separate list object to solve the problem.

Upvotes: 13

Views: 6808

Answers (4)

Alexander 17
Alexander 17

Reputation: 1

class A :
    content = []
    def __init__(self, *p) :
        self.content = p
    def __iter__(self):
        for i in range(len(self.content)) :
            yield self.content[i]

a = A(1, 2, 3)

print(tuple(a))
print(list(a))

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798616

There is no direct counterpart, but list() is implemented by iterating over the argument. So implement either the iterator protocol (__iter__()) or repeated indexing (__getitem__()).

Upvotes: 28

Alexander 17
Alexander 17

Reputation: 1

class A (list) :
    def __iter__(self):
        for i in range(len(self)):
            yield self[i]

a = A([1, 2, 3])

print(tuple(a))

Upvotes: -1

Fabio Goncalves
Fabio Goncalves

Reputation: 81

Generator:

def __iter__(self):
    return (i for i in [1,5,6,8])

List:

def __iter__(self):
    return iter([1,5,6,8])

Tuple:

def __iter__(self):
    return iter((1,5,6,8))

Upvotes: 3

Related Questions