[Tutor] Defining "bit" type

Vicent vginer at gmail.com
Sat Jan 24 20:03:42 CET 2009


On Sat, Jan 24, 2009 at 19:48, bob gailer <bgailer at gmail.com> wrote:


> The problem is: there is no way that I know of to add fundamental types to
> Python. Also realize that variables are dynamically typed - so any
> assignment can create a variable of a new type. That is why a = 0 results in
> an int.
>
> So one must resort, as others have mentioned, to classes.
>

Yes, that's what I understood from previous answers.



> Framework (untested):
>
> class Bit:
>   _value = 0 # default
>   def __init__(self, value):
>     self._value = int(bool(value))
>   def getvalue(self):
>     return self._x
>   def setvalue(self, value):
>     self._x = int(bool(value))
>   value = property(getvalue, setvalue)
>   def __add__(self, other): # causes + to act as or
>     self._value |= other
>   def __mul__(self, other): # causes * to act as and
>     self._value &= other
>
> b = Bit(1)
> b.value # returns 1
> b.value = 0
> b.value # returns 0
> b.value + 1 # sets value to 1
> b.value * 0 # sets value to 0
>
>
Wow! that's great. I'll give it a try.

It would be great if   "b.value = 0"   could be just written as "b = 0"
without changing type as a result.

What happens if every time I want to update the value of "b", I use "b=
Bit(0)" , "b=Bit(1)", and so on?? Is like "building" the object each time?
It is less efficient, isn't it?

You are going to kill me, but... Maybe the solution is not to re-define what
already exists —boolean data type, but just using it, as suggested at the
beginning of the thread...

b = bool(1)
b = bool(0)

After all, it's not so bad...

I'll think about it.

--
Vicent
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090124/8322b066/attachment.htm>


More information about the Tutor mailing list