Add methods to int?

Peter Otten __peter__ at web.de
Wed Jun 16 19:44:54 CEST 2004


Reinhold Birkenfeld wrote:

> I found this recipe at the Python cookbook:
> 
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81732
> 
> Saucily I tried to apply this to int or str, with this result:
> 
> TypeError: object does not support item assignment
> 
> Any way to go round that?

int and str have no __dict__, neither in the class nor instance, and hence
no place to store your additions: 

>>> "__dict__" in dir(4)
False
>>> "__dict__" in dir(4 .__class__) 
False

Therefore you have to subclass them to gain the ability to add methods:

>>> class Int(int):
...     def __new__(cls, n):
...             return int.__new__(cls, n)
...
>>> x = Int(2)
>>> x.twice()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'Int' object has no attribute 'twice'

Now let's grow our Int class a twice() method:

>>> def twice(self): return 2*self
...
>>> Int.twice = twice
>>> x.twice()
4
>>>

I don't know for sure, but I suppose the tricks used in the recipe are no
longer necessary in current Python. Anyway, if you want to tack your custom
methods on the builtin integer and string classes, you're out of luck.

Peter




More information about the Python-list mailing list