Controlling assignation

Peter Hansen peter at engcorp.com
Mon Jun 13 12:56:56 EDT 2005


Xavier Décoret wrote:
> What I wanted to do is something like this:
> 
> def change(x,v):
>     x = v
> 
> class A(object):
>     def __init__(self,v):
>         self.x = v
> 
> a = A(3)
> print a.x  # displays 3
> change(a.x,4)
> print a.x  # still displays 3

How about this?

def change(x, v):
     x.x = v

Then call it with

change(a, 4)

And print a.x will return 4 as you wish.

> It may seem weird, but I ensure there is a reason for doing this. In C++ 
> (the language I am mot familiar with), I could define f to take a 
> pointer to member function of a class, a pointer and a value and achieve 
> what I want. 

In Python the closest match to this might be to pass the reference to 
the object, plus the *name* of the attribute, as a string.

def change(obj, attr, v):
     setattr(obj, attr, v)

This, of course, is now a useless function since that's what "setattr" 
already does...

So:

a = A(3)
print a.x  # displays 3
setattr(a, 'x', 4)
print a.x  # displays 4

-Peter



More information about the Python-list mailing list