Integers have docstring for int()

Peter Otten __peter__ at web.de
Thu Aug 12 08:45:33 EDT 2004


Peter Abel wrote:

> The following seems to be unaccustomed, but it's good Python:
> 
>>>> class myInt(int):
> ...         """Instance of myInt"""
> ...         def __init__(self,val):
> ...                 self=int(val)
> ...
>>>> i=myInt(10)

Minor nit: assigning to self has no effect. you can leave out the above
__init__() altogether.

>>> class myInt(int):
...     "instance of myInt"
...
>>> mi = myInt(10)
>>> mi
10
>>> type(mi)
<class '__main__.myInt'>
>>>

As int is immutable, all the "interesting stuff" has to be performed in
__new__().

A more detailed view of what is going on in __init__():

>>> class myInt(int):
...     def __init__(self, val):
...             print "val-id", id(val)
...             print "self before assignment", id(self)
...             self = int(val)
...             print "self after assignment", id(self)
...
>>> mi = myInt(1000)
val-id 135719460
self before assignment 1076456780
self after assignment 135719460
>>> id(mi)
1076456780
>>>

I. e. you create an integer from another integer and immediately throw it
away. I used 1000 because some low numbers are "interned". For them
"val-id" and "self after assignment" would have been the same.

Peter




More information about the Python-list mailing list