can a method access/set another's variables?
Michael Hoffman
cam.ac.uk at mh391.invalid
Sun Apr 1 21:43:37 EDT 2007
asdf1234234 wrote:
> -a.py-
> import b
>
> class A:
> def __init__(self):
> pass
> def my_method(self):
> var = 1
> self.var = 2
> b.set_var(self)
> print var
> print self.var
>
> my_a = A()
> my_a.my_method()
>
> -b.py-
> def set_var(self):
> var = 2
> self.var = 2
>
> I want both var and self.var to be 2 at the end. Is there anything I
> can pass to set_var() that will give it access to the variables in
> my_method() like I can use self for the variables in the class A?
I hope there isn't a way to do this that simply. :) Why do you want to
do this, or is it idle curiosity? There is almost surely a better way to
solve your underlying problem.
You can *read* your caller's local variables (either pass locals() as an
argument or use inspect to get the frame locals), but writing to this
dictionary has undefined behavior.
--
Michael Hoffman
More information about the Python-list
mailing list