Skip to content Skip to sidebar Skip to footer

How Do I Make A Custom Class A Collection In Python

I come from a Matlab background. In matlab I can create a class definition and then create an array of objects. I can easily dereference each object with an index. In addition,

Solution 1:

When programming in Python, performing type checks isn't incredibly common. Are you positive you need your list to only accept one type (and its subtypes), or will you trust the programmer to read your docs and not put something in that's not supposed to be there?

If so, here's an example generic class that inherits from collections.MutableSequence that would probably do what you want:

from collections import MutableSequence
classVerifierList(MutableSequence):
    _list = Nonedef__init__(self, allowedClasses, *args, **kwargs):
        super(VerifierList, self).__init__()
        self._list = list(*args, **kwargs)
        self.allowedClasses = tuple(allowedClasses)
    def__repr__(self):
        returnrepr(self._list)
    def__str__(self):
        returnstr(self._list)
    def__len__(self):
        returnlen(self._list)
    def__getitem__(self, index):
        return self._list[index]
    def__setitem__(self, index, value):
        ifnotisinstance(value, self.allowedClasses):
            raise TypeError('Value of type %s not allowed!' % value.__class__.__name__)
        self._list[index] = value
    def__delitem__(self, index):
        del self._list[index]
    definsert(self, index, value):
        ifnotisinstance(value, self.allowedClasses):
            raise TypeError('Value of type %s not allowed!' % value.__class__.__name__)
        self._list.insert(index, value)

Use it as follows:

>>> classA(object): pass>>> classB(object): pass>>> l = VerifierList((A,))
>>> l.append(A())
>>> print(l)
>>> [<__main__.A object at 0x000000000311F278>]
>>> l.append(B())

Traceback (most recent call last):
  File "<pyshell#228>", line 1, in <module>
    l.append(B())
  File "C:\Python27\lib\_abcoll.py", line 661, in append
    self.insert(len(self), value)
  File "<pyshell#204>", line 23, in insert
    raise TypeError('Value of type %s not allowed!' % value.__class__.__name__)
TypeError: Value of type B not allowed!

Solution 2:

All such capabilities in Python use "Special method names" as described in the Language Reference section 3.3. Section 3.3.6 describes how to emulate container types, which in general is what you're asking for here. You need to define and implement methods __getitem__, __setitem__,__delitem__ and perhaps also __iter__, __reversed__ and __contains__. Python is quite good for this and the approach is very flexible.

Post a Comment for "How Do I Make A Custom Class A Collection In Python"