Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 496
rohithpr Avatar asked May 31 '15 06:05

rohithpr


People also ask

How do I get list of methods in a Python class?

To list the methods for this class, one approach is to use the dir() function in Python. The dir() function will return all functions and properties of the class.

Can you have a list of objects in Python?

We can create list of object in Python by appending class instances to list. By this, every index in the list can point to instance attributes and methods of the class and can access them. If you observe it closely, a list of objects behaves like an array of structures in C.

How do you create a list inside a class in Python?

Creating lists in Python can take place by just placing the sequence inside the square brackets[].


1 Answers

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

like image 139
Ignacio Vazquez-Abrams Avatar answered Sep 24 '22 18:09

Ignacio Vazquez-Abrams