Search code examples
pythonclassobjectencapsulationinteraction

Python object interaction


So, programming in Python 3, I've got a program with a problem whose essence I've distilled in this (non)functional piece of code:

class One:
    def __init__(self):
        self.var1 = 1

    def change(self):
        two.var2 = 5

class Two:
    def __init__(self):
        one = One()
        self.var2 = 2
        one.change()

two = Two()

The IDLE interpreter throws:

> Traceback (most recent call last):
  File "C:/-", line 15, in <module>
    two = Two()
  File "C:/-", line 12, in __init__
    one.change()
  File "C:/-", line 6, in change
    two.var2 = 5
NameError: name 'two' is not defined

Apparently, doing this instead:

class One:
    def __init__(self):
        self.var1 = 1

    def change(self):
        two.var2 = 5

class Two:
    def __init__(self):
        self.var2 = 2
        one.change()

one = One()
two = Two()

...doesn't help, as it gives me the exact same type of error. I really don't understand why this is happening... or how to structure it differently. I think the last time I had a problem like this I avoided it by nesting classes (rather messy and worked for only one level of nesting, as far as I can remember), but I'd really like to know how to make these two objects communicate with each other properly.

Edit: What I have is a program whose only line of code instantiates a main class, let's call it "Earth". In this program-object everything happens, included the instantiation of other classes; let's assume it's only one in this case, and call it "Moon". What I want to do is have this object Moon be able to change the Earth's states, its different variables.


Solution

  • As I see it, you just have to pass to one.change() which object you want to change

    class One:
        def __init__(self):
            self.var1 = 1
    
        def change(self, two):
            two.var2 = 5
    
    class Two:
        def __init__(self):
            self.var2 = 2
            one.change(self)
    
    
    one = One()
    two = Two()