Can a method in one class change an object in another class?

Kent Johnson kent37 at tds.net
Sun Mar 6 08:54:18 EST 2005


Stewart Midwinter wrote:
> I've got an app that creates an object in its main class (it also
> creates a GUI).  My problem is that I need to pass this object, a
> list, to a dialog that is implemented as a second class. I want to
> edit the contents of that list and then pass back the results to the
> first class.   So my question is, can a method in one class change an
> object in another class?

Diez and Lee have shown you two ways to do this.

> If the answer is no, I suppose I could pass in the list as an argument
> when I create the second class, then return the contents of the list
> when I end the methods in that second class.

This is almost what your example does, but you have made a small error. See below.

> alternatively, I could make the list a global variable, then it would
> be available to all classes.  I have a nagging feeling though that
> global variables are to be avoided on general principle. Is this
> correct?

Yes, it is correct.

> Here's a simple example app that tries to have one class change the
> object in another class.  It doesn't give the behaviour I want,
> though.
> 
> ---
> #objtest.py
> 
> class first:
>     def __init__(self):
>         a = 'a'
>         self.a = a
>         print self.a
> 
>     def update(self):
>         print 'initially, a is', self.a
>         self.a = second(self.a)

The line above is creating an instance of second and assigning it to self.a. What you want to do is 
create an instance of second, *call* it, and assign the result to self.a. So you should have
           self.a = second(self.a)(self.a)

The self.a parameter passed to second is never used. If you change second.__init__ to
       def __init__(self):
           pass

then the call in update() will be
           self.a = second()(self.a)

Kent
>         print 'afterwards, a is', self.a
> 
> class second:
>     def __init__(self, a):
>         pass
> 
>     def __call__(self, a):
>         a = 'aa'
>         return a
> 
> if __name__ == '__main__':
>     app = first()
>     app.update()
> 
> thanks,
> --
> Stewart Midwinter
> stewart at midwinter.ca
> stewart.midwinter at gmail.com



More information about the Python-list mailing list