Vicent wrote:
Hello.

As fas as I know, there is a "bytes" type in Python 3, which is a sequence of bytes.

Anyway, I am working with Python 2.5.4, and I am interested in defining a new type called "bit" (if possible), which represents a number that can only take values 0 or 1 —that's what we would call a "binary variable", in a Mathematical Programming context.

I want to define that new data type within my code, so that I can use it in the same way I would use "int", "long" and "float" data types, for instance.

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. 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




--
Bob Gailer
Chapel Hill NC
919-636-4239
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to