Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I create a custom list class in python?

Tags:

python

list

I would like to write a custom list class in Python (let's call it MyCollection) where I can eventually call:

for x in myCollectionInstance:     #do something here 

How would I go about doing that? Is there some class I have to extend, or are there any functions I must override in order to do so?

like image 635
K Mehta Avatar asked Jul 03 '11 00:07

K Mehta


People also ask

How do you create a class list 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 in Python?

In Python, a list is created by placing elements inside square brackets [] , separated by commas. A list can have any number of items and they may be of different types (integer, float, string, etc.). A list can also have another list as an item.

What is a custom class in Python?

Creating a Custom Class in Python Using a Constructor A class is a collection of objects. It is a data structure defined by the user, created with the keyword class to keep related things together. So, a class is a grouping of object-oriented constructs.

Can we create set of list in Python?

Creating Python Sets But a set cannot have mutable elements like lists, sets or dictionaries as its elements.


1 Answers

Your can subclass list if your collection basically behaves like a list:

class MyCollection(list):     def __init__(self, *args, **kwargs):         super(MyCollection, self).__init__(args[0]) 

However, if your main wish is that your collection supports the iterator protocol, you just have to provide an __iter__ method:

class MyCollection(object):     def __init__(self):         self._data = [4, 8, 15, 16, 23, 42]      def __iter__(self):         for elem in self._data:             yield elem 

This allows you to iterate over any instance of MyCollection.

like image 99
jena Avatar answered Sep 29 '22 03:09

jena