Tapping into the access of an int instance

David wizzardx at gmail.com
Thu Sep 20 22:14:30 CEST 2007


On 9/20/07, Tor Erik Sønvisen <torerik81 at gmail.com> wrote:
> Hi,
>
> 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...

You can cheat in your example by overriding the __str__ method. That
method (or __repr__) is what gets called from the interpreter to
display your variable.

You can also override the __int__ method. Then int(i) can return a
custom value.

You can also do something close to what you want with properties:

x = X() # Where X is a class with appropriate setter and getter methods
x.i = 5
print x.i # Outputs something besides 5

However, it sounds like you want the equivalent of a non-existant
__getvalue__ method that you could override to return a custom value
instead of the one you initialised the variable with. Like a kind of
"proxy to self" method. However, Python variables don't work that way
:-)



More information about the Python-list mailing list