The curious behavior of integer objects

Calvin Spealman ironfroggy at gmail.com
Mon Jan 15 17:50:56 EST 2007


As it turns out, this has little to do with integers and the
operations you are trying to do on them. I'll explain in more detail.

Integers are immutable, which you may already know. This presents a
problem with subclassing them and using the usual special method
__init__, because the int object has already been created by this
point and can not change. Another special method, __new__, is called
passing the class object itself (foo, in this case) for the first
argument (traditionally named cls, instead of self). The return of
this should be an integer which will be the value of your new foo
int-subclass.

The following will do as you expected your own example to do.

class foo(int):
    def __new__(cls, value):
        return value & 0xF

assert foo(0x10) == 0  # Assertions are much better tests than prints :-)

On 1/15/07, Jim B. Wilson <wilson at afn.org> wrote:
> Am I nuts? Or only profoundly confused? I expected the this little script
> to print "0":
>
> class foo(int):
>   def __init__(self, value):
>     self = value & 0xF
>
> print foo(0x10)
>
> Instead, it prints "16" (at least on python 2.4.4 (Linux) and 2.5 (Wine).
>
> Jim Wilson
> GNV, FL
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://ironfroggy-code.blogspot.com/



More information about the Python-list mailing list