Custom 'Float' class. Am I right here?

Terry Reedy tjreedy at udel.edu
Wed Jul 16 19:56:02 EDT 2008



Prashant Saxena wrote:
> import sys
> 
> class Float(float):
>     """
>     Custom float datatype with addtional attributes.
>     """
> 
>     def __new__(self,
>                         value=0.0, #default value
>                         name='', # string
>                 & nbsp;       range=(0.0, 1.0) # tuple
>                         )
>                        
>         try:
>             self.name = name
>             self.range = range
>             self.pos = (1, 1)
>             return float.__new__(self, value)
>         except:
>              print ('Invalid value : Float = %s %s' % (str(value), 
> sys.exc_info()[:2]))
> 
>    
>     def setpos(self, value):
>         self.pos = value
>     def getpos(self):
>         return self.pos*2.0
>     p = property(getpos, setpos)
> 
> myFloat = Float(0.23)
> print myFloat.pos
> 
> I am trying to create a custom 'float' datatype by subtyping default 
> 'float'. There are few things I would like to know here:
> 
> 1. How to make 'name' & 'range' only readable attributes.

A property with a working get and set that raises an exception.

> 2. The property 'p' is not working as it has to. What's wrong here?

Don't know.

> 3. I would be heavily instancing this class, and I won't be creating any 
> new attribute on instance. Is there any way to optimize? __slots__?

I believe this is what slots is for.




More information about the Python-list mailing list