ctypes module, question on Arrays

Josh mlsj at earthlink.net
Wed Mar 19 04:31:31 CET 2003


Hi,

I have been trying to design a class which is inherited from the Array 
class in the ctypes module. Surprisingly, I cannot set the length of the 
array at runtime:

This does not work:

from ctypes import *

class Darray(Array):
    	_type_=c_double
    	
    	def __init__(self,len):
  	    	self.__class__._length_=len

Traceback (most recent call last):
  File "<pyshell#15>", line 1, in ?
    class varr(Array):
AttributeError: class must define a '_length_' attribute, which must be a 
positive integer

The only solution seems to be to set the _length_ in the class 
definition at design time like so:

class Darray(Array):
    	_type_=c_double
      _length_= 6 #Any dummy value  	
    	def __init__(self,len):
  	    	self.__class__._length_=len #And change the _length_ when     
	    	    	    	    	    	    #instantiating the class

When I do that, this happens:

>>>foo=Darray(10)

>>>foo._length_
>>>10
>>> d[8]
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in ?
    d[8]
IndexError: invalid index

Why can't I access d[8] when I changed the length to 10 while 
instantiating? What's going on? And how can I set the length of the array 
at runtime?

Thanks in advance


    	






More information about the Python-list mailing list