[ctypes-users] Extending a ctype to put into a structure
Brought to you by:
theller
From: Guillaume P. <gui...@sc...> - 2005-01-12 03:27:40
|
Hi, I wanted to do the following thing: Create a subclass of c_int that could be used to transparently get a formatted string from the integer when accessing the value property. However it does not work as expected if used from a structure. class usdollars(c_int): def valueget(self): intval=super(usdollars,self).value return self._format(intval) def valueset(self,newvalue): setattr(super(usdollars,self),'value',newvalue) value=property(valueget,valueset) def _format(self,value): s='%03d'%value decpart=s[-2:] if int(decpart)==0: decpart='' else: decpart='.'+decpart integerpart=s[:-2] parts=[] while len(integerpart)>3: parts.append(integerpart[-3:]) integerpart=integerpart[:-3] parts.append(integerpart) parts.reverse() return '$'+','.join(parts)+decpart def __repr__(self): return "usdollars(%s)"%self.valueget() Then I use it with >>> a=usdollars(100000) >>> a.value '$1,000' but if i do: >>> class test(Structure): ... _fields_ = [ ('money',usdollars) ] ... >>> b=test() >>> b.money=100000 >>> b.money 100000 And not '$1,000' as I hoped. also assigning the attribute value does not work as hoped >>> a.value=1000 Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 6, in valueset TypeError: 'super' object has only read-only attributes (assign to .value) How do ctypes Structure implement its properties? It is not a big issue because easy to workaround. It would be fantastic though to inherit from ctypes native types! Regards, Guillaume -- Guillaume Proux (ギヨム・プル) アジア事業部 シニア マネージャー Scala Inc. -- http://www.scala.com/ |