[Tutor] Limiting variable size

Gregor Lingl glingl at aon.at
Mon Jan 26 15:11:38 EST 2004



Daniel Ehrenberg schrieb:

>Scott wrote:
>  
>
>>Is there a way to set the maximum numeric value of a
>>variable?  I want x
>>to roll over if it gets to over four bytes. 
>>
>I don't think there's a way to do it besides just
>doing a mod like below:
>
>x %= 4294967296 #four bytes
>
>This will only work when you explicitly do this on a
>value; it won't overflow automatically. 
>
Two days ago Karl taught me how to use __new__ for subclassing tuple.
A similar approach could be done here (In my example I use 10 instead of 
2**32)

 >>> class boundedInt(int):
        def __new__(cls, n):
            return int.__new__(cls, n%10)
        def __add__(self, other):
            return boundedInt( int.__add__(self,other) )

 >>> a = boundedInt(14)
 >>> a
4
 >>> b = boundedInt(19)
 >>> b
9
 >>> a+b
3
 >>>

Just a funny idea. (But very probably not what you want (or need))
Nevertheless: it seems that studying "New Classes" could be rewarding.

Gregor







More information about the Tutor mailing list