can a method access/set another's variables?

7stud bbxx789_05ss at yahoo.com
Mon Apr 2 05:01:39 CEST 2007


On Apr 1, 7:56 pm, "wswilson" <wswil... at gmail.com> wrote:
> On Apr 1, 9:43 pm, Michael Hoffman <cam.ac... at mh391.invalid> wrote:
>
>
>
> > 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
>
> I am parsing a document which contains some lines with code I want to
> eval or exec. However, due to the complexity of the parsing, I am
> splitting it among different methods. So, if I eval something in one
> method, it won't be there if I try to access its value a few lines
> later since I happen to be in a different method in the parser. Thanks
> for the help!

class A(object):
        def early_parse(self):
                self.result1 = eval("10 + 5")

class MyParser(object):
        def later_parse(self):
                MyParser.a.result2 = MyParser.a.result1 + eval("20 *
2")

        a = A()

p = MyParser()
p.a.early_parse()
p.later_parse()
print p.a.result1
print p.a.result2




More information about the Python-list mailing list