Tapping into the access of an int instance
Peter Otten
__peter__ at web.de
Fri Sep 21 04:41:42 EDT 2007
Tor Erik Sønvisen wrote:
> Does anyone know how to interrupt the lookup of an integer value? I
> know I need to subclass int, since builtin types can't be altered
> directly...
>
> Below is how far I've come... What I want is to tap into the access of
> instance i's value 1...
>
>>>> class Int(int):
> def __init__(self, *a, **k):
> super(Int, self).__init__(self, *a, **k)
>
>
>>>> i = Int(1)
>>>> i
> 1
You may be looking for __new__() which is invoked before an object is
created. This is particular useful for immutables like int.
>>> lookup = {}
>>> class Int(int):
... def __new__(cls, value, *more):
... if not more:
... try:
... return lookup[value]
... except KeyError:
... pass
... return int.__new__(cls, value, *more)
...
>>> lookup["answer"] = Int(42)
>>> Int("answer")
42
>>> type(_)
<class '__main__.Int'>
Peter
More information about the Python-list
mailing list