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

Diez B. Roggisch deetsNOSPAM at web.de
Sun Mar 6 12:33:13 CET 2005


> 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?


Sure it can. But your code shows that you suffer from a fundamental
misunderstanding on how variables and values work in python. Don't be to
worried about that, it happens to quite a few people. 

A variable in python is just a name refering to an object. So this

>>> a = 'a'
>>> b = a
>>> print a, b
a a


will make a and b both refer to the string 'a'. Now assigning a different
value to b will not affect the binding of a:

>>> b = 10
>>> print a, b
a 10

So that is the reason you obeserve the behaviour you've seen. Now the
question is how to accomplish your desired goal? The answer is simple:
don't rebind a value to a name - alter the value! In python, there is a
distinction between mutable objects and immutable ones. Strings and numbers
are of the latter kind, lists and dicts and objects of the former. So if we
changed our example slighly, things start working as you'd expect:

>>> a = ['a']
>>> b = a
>>> print a,b
['a'] ['a']
>>> b[0] = 10
>>> print a, b
[10] [10]

So if you pass the same _mutable_ object to two objects, and one of them
changes it, the other one will see the changes:

class A:
    def __init__(self):
        self.a_list = [0]

class B:
    def __init__(self, l):
        self.l = l

    def foo(self):
        self.l.append(100)

a = A()
b = B(a.a_list)
b.foo()
print a.a_list

-> [0, 100]


There are some resources on the web that explain this in more thourough
detail - but curretntly I have trouble finding them. Search this newsgroup.
-- 
Regards,

Diez B. Roggisch



More information about the Python-list mailing list