Reputation: 25
I am trying to share variables between two separate modules in python. In general what I am trying to do is,
class A:
def __init__(self):
self.set1 = 0
self.set2 = 0
def count(self, data):
parse throught the data in here...
self.set1 = data[0:2]
self.set2 = data[5:20]
--------------------------------------------
from moduleA import A
def main():
data = A()
print(data.set1)
print(data.set2)
if __name__ == '__main__': main()
but this will not work. it will just print 0 for set1 and set2. i'm not sure how I would get the correct results.
Does anyone know the right approach to solve my problem?
Thanks in advance!
Upvotes: 0
Views: 2441
Reputation: 7555
You are never calling count(...)
, the values of set1
and set2
will be 0 until you do.
You call __init__(self)
by instantiating the class with the line:
data = A()
This sets both data.set1
and data.set2
to 0.
Update: following OP's comment.
When you create a new A
object in your main module, you are creating a new instance of that object. Each instance has it's own version of its attributes, so if I did:
data1 = A()
data2 = A()
data1.set1 = "some value"
Then the following would be false:
data1.set1 == data2.set1
Both objects get their own set of instance attributes.
To acheive what you want, you can do two (sensible) things:
ModuleA
and that all the other modules useIf will elaborate or both below.
Class Attributes
If you declare an attribute in the class definition, instead of the `init(self, ...) method, those attributes are shared between every instance, at least initially.
An example:
class A(object):
a = []
Now if I do this:
data1 = A()
data2 = A()
data1.a.append('some value')
Then data1.a
and data2.a
will both be the same list, with the same values.
Like I said, this is only initially, if you ever assign to a
, then they will be referencing different things, and won't be the same. I could re-bind data1.a
to something else, and data2.a
would have the original value:
data1.a = ["another value"]
print(data1.a) # prints ["another value"]
print(data2.a) # prints ["some value"]
If you want all A
objects to share that attribute value, you must never assign to it for a particular instance, because then that instance will have its own value.
"Singleton" object
Instead of creating a new object data
in main, you could declare a single object of type a in ModuleA
:
class A(object):
...
data = A()
Now, in your main module you can use it like this:
from ModuleA import data
print(data.set1)
But you must always ensure that all your modules use that single object, and don't create their own A
s.
Upvotes: 4