default behavior

John Nagle nagle at animats.com
Thu Jul 29 15:28:18 EDT 2010


On 7/29/2010 11:12 AM, wheres pythonmonks wrote:
> Why is the default value of an int zero?
>
>>>> x = int
>>>> print x
> <type 'int'>
>>>> x()
> 0
>>>>
>
> How do I build an "int1" type that has a default value of 1?


 >>> class int1(object) :
...    def __init__(self) :
...       self.val = 1
...    def __call__(self) :
...       return(self.val)
...
 >>> x = int1()
 >>> x()
1

This isn't useful; you'd also have to define all the numeric operators
for this type. And then there are mixed-type conversion issues.

Inheriting from "int" is not too helpful, because you can't assign
to the value of the base class.  "self=1" won't do what you want.

[Hopefully no speed penalty.]
In your dreams.  Although all numbers in CPython are "boxed",
so there's more of a speed penalty with "int" itself than you
might expect.  There are some C libraries for handling large
arrays if you really need to crunch numbers.

				John Nagle




More information about the Python-list mailing list