I would like to inherit from a list to produce the myList class, that only accepts one specific type of object (say ints).
I am sure decorators can do that elegantly.
-
Why not inherit from list and override extend, append, and init, only with type checking to raise an error if an object of the wrong type is added?twneale– twneale2010-08-02 21:55:25 +00:00Commented Aug 2, 2010 at 21:55
-
Sure. This is my first solution. I was just wondering if there was a more generic solution ; I mean a unique solution for any type of object.NiKo– NiKo2010-08-03 08:36:59 +00:00Commented Aug 3, 2010 at 8:36
Add a comment
|
1 Answer
What about using arrays?
This module defines an object type which can compactly represent an array of basic values: characters, integers, floating point numbers. Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The type is specified at object creation time by using a type code, which is a single character. The following type codes are defined:
2 Comments
NiKo
Mmmmm... Can an array store any type of object (instances of my own classes)?
heltonbiker
Yes, one of the types accepted by arrays are 'object', and since everything in Python are objects... Indeed it is the perfect (and only, afaik) way to create heterogeneous sequences.