Add methods to int?

Reinhold Birkenfeld reinhold-birkenfeld-nospam at wolke7.net
Wed Jun 16 14:05:05 EDT 2004


Peter Otten wrote:

> 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

So why does "print int.__dict__" produce a value?

> 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

That's clear, yes. But the problem with this solution is that I must
convert all literals to Int before using them.

Reinhold

-- 
Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows
mitbrächte, wäre das bedauerlich.  Was bei Windows der Umfang eines
"kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk.
  -- David Kastrup in de.comp.os.unix.linux.misc



More information about the Python-list mailing list