Extending long

Russell Blau russblau at hotmail.com
Wed Jun 19 17:50:00 EDT 2002


"Martin v. Loewis" <martin at v.loewis.de> wrote in message
news:m3ofe7q902.fsf at mira.informatik.hu-berlin.de...
> estama at dblab.ntua.gr (Freeman Stopjohn) writes:
>
> > class bitnum(long):
> >     def getbit(self,bitn):
> >         if self & (1 << bitn) >0:
> >             return 1
> >         else:
> >             return 0
> >     def setbit(self,bitn):
> >         self=self ^ ( 1 << bitn )
> > -----
> >
> >  The getbit method works ok.
> >  The setbit doesn't (it doesn't change the number).
> >
> >  What am i doing wrong?
>
> You are assigning to self. self is a parameter of setbit, just like
> bitn. Assignments to formal parameters have no effect.
>
> What you want to do cannot be done; long objects are immutable. I
> recommend you implement a wrapper, rather than inheriting.

How about:

    def setbit(self,bitn):
        return bitnum(self ^ ( 1 << bitn ))

This will not modify the bitnum() instance in place, since (as you
pointed out) such an instance is immutable, but it will return a new
instance with the desired value.

--
I don't actually have a hotmail account; but I do have one on excite.com
if you really want to get in touch with me.






More information about the Python-list mailing list