Python: Sharing Variables Between Modules
Solution 1:
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:
- Store the data on the class itself
- Have a singleton object that is declared in
ModuleA
and that all the other modules use
If 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.
Post a Comment for "Python: Sharing Variables Between Modules"