Initializing with the correct type
szabi
szabolcs.berecz at gmail.com
Thu Dec 7 09:25:32 EST 2006
aine_canby at yahoo.com írta:
> Hi all,
>
> I'm new to Python and I'm just wordering if my approch is correct.
> Here's an example. I'm making sure that the length and types are
> correct. This is in case I use such a class and accidently pass it the
> wrong object.
>
> class Funkt:
> 'Funkt Class'
>
> def __init__(self, L):
> 'Constructer, accepts a list L of ints, which is 1 or listLength in
> length'
> if len(L) not in (1,listLength):
> errorString = "Format Error: L must be 1"
> if listLength != 1:
> errorString += " or "+str(listLength)
> errorString += " in Length"
> raise FormatError,errorString
> for i in L:
> if type(i) is not int:
> raise FormatError, "L must contain ints"
if you need something for holding only ints, you could use the array
module:
>>> import array
>>> a = array.array('i')
>>> a.append(10)
>>> a.append('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: an integer is required
>>> type(a)
<type 'array.array'>
>>>
Szabi
More information about the Python-list
mailing list