Transferring variables between classes

0 votes
asked Dec 31, 2010 by calccrypto

I have 2 classes that operate on the same variables but do the inverse of each other. Is there a way to transfer the variables between them without hard coding every exchange or combining all the values into one array? Combining the classes is not an option.


class class1:
   def __init___(self):
      # code
      initialize variable MAIN

   # do stuff
   # do stuff
   make variable stuff
   # do stuff
   make variable thing
   # do stuff

class class2:
   def __init___(self):
      # code
      initialize variable stuff
      initialize variable thing
   # do stuff
   # do stuff
   undo variable stuff
   # do stuff
   undo variable thing
   # do stuff
   make variable MAIN

I want to be able to send data back and forth between class1 to class2 quickly.

1 Answer

0 votes
answered Dec 31, 2010 by lennart-regebro

I think this is much easier than you think. Here is some examples of "sending" data between two classes.

class class2(object):
    def __init__(self, other):
        self.other = other

    def set_color(self, color):
        self.color = color
        # "Sending" to other class:
        self.other.color = color

    def set_smell(self, smell, associated_object):
        self.smell = smell
        associated_object.smell = smell

Usage like this:

>>> ob1 = class1()
>>> ob2 = class2(ob1)
>>> ob2.set_color("Blue")
>>> ob1.color

>>> ob2.set_smell("Good", ob1)
>>> ob1.smell
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter