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?
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.
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.
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.
Creating Python Sets But a set cannot have mutable elements like lists, sets or dictionaries as its elements.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With