Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass variables between class instances or get the caller?

Tags:

python

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

class bar():
  def __init__(self):
    print "foo var1"

f = foo()
b = bar()

In foo, I am doing something that produces "var1" being set to 1 In bar, I would like to access the contents of var1

How can I access var1 in the class instance f of foo from within the instance b of bar

Basically these classes are different wxframes. So for example in one window the user may be putting in input data, in the second window, it uses that input data to produce an output. In C++, I would have a pointer to the caller but I dont know how to access the caller in python.

like image 652
lme Avatar asked Sep 21 '11 14:09

lme


2 Answers

As a general way for different pages in wxPython to access and edit the same information consider creating an instance of info class in your MainFrame (or whatever you've called it) class and then passing that instance onto any other pages it creates. For example:

class info():
    def __init__(self):
        self.info1 = 1
        self.info2 = 'time'
        print 'initialised'

class MainFrame():
    def __init__(self):
        a=info()
        print a.info1
        b=page1(a)
        c=page2(a)
        print a.info1

class page1():
    def __init__(self, information):
        self.info=information
        self.info.info1=3

class page2():
    def __init__(self, information):
        self.info=information
        print self.info.info1

t=MainFrame()

Output is:

initialised
1
3
3

info is only initialised once proving there is only one instance but page1 has changed the info1 varible to 3 and page2 has registered that change.

like image 149
Rowan Avatar answered Oct 01 '22 19:10

Rowan


No one has provided a code example showing a way to do this without changing the init arguments. You could simply use a variable in the outer scope that defines the two classes. This won't work if one class is defined in a separate source file from the other however.

var1 = None
class foo():
  def __init__(self)
    self.var1 = var1 = 1

class bar():
  def __init__(self):
    print var1

f = foo()
b = bar()
like image 36
AcidTonic Avatar answered Oct 01 '22 19:10

AcidTonic