Reputation:
In my Java I have a central boot loader which keeps on boot all default values as public static or private static, and later when require I can go to other class/threads and access them to do modify etc. For example:
public class main extends JWindow implements MouseListener, MouseMotionListener {
private static boolean isDetect = true;
public static String vncMode = "1980";
...
public main() {
vncMode = C.readIni("vncmode"); // 1980
}
}
public class TCPHandler implements Runnable {
import main.*;
public void run() {
if (main.vncMode.equals("1999" ) ||
main.vncMode.equals("2013")) {
echo(main.vncMode, RED);
} else {
echo(main.vncMode, GREEN);
}
}
}
Similar to Java, in Python, How can i set public static/private static declarations, so that i can have access from any other class of that value?
python1.py:
from bgcolors import bgcolors
class Python1(object):
isDetect = True
def run(self):
# expecting vncMode = 1980
print bgcolors.RED + "we are now in 1999: from version: " + vncMode
python2.py:
from bgcolors import bgcolors
class Python2(object):
isDetect = True
def run(self):
# expecting vncMode = 1980
print bgcolors.RED + "we are now in 2013: from version: " + vncMode
main.py:
from bgcolors import bgcolors
from python1 import Python1
from python2 import Python2
vncMode = "1980"
a = Python1()
a.run()
b = Python2()
b.run()
How can i set the value 1980 and in all class get 1980 ?
Upvotes: 0
Views: 77
Reputation: 2932
While I would normally use an argument to __init__
, and explicitly pass the value to each instance upon creation, python has the global
keyword to do something along the lines of what you are asking.
a_name = "A Value"
class Sample(object):
def a_method(self):
global a_name
print a_name
sample_instance = Sample()
sample_instance.a_method() # prints "A Value"
but you really should do something like...
a_name = "A Value"
class Sample2(object):
def __init__(self, value):
self.value = value
def a_method(self):
print self.value
sample_instance = Sample2(a_name)
sample_instance.a_method() # prints "A Value"
Upvotes: 0
Reputation: 60147
If you have a container that stores the attributes you want to share
# example, could be a simple tuple, a full class or instance or dictionary, etc.
attributes = namedtuple("attributes", "vncmode")("1980")
you can pass the attributes to all of the classes on initialisation:
class ...:
def __init__(self, attributes, ...):
self.attributes = attributes
and then the instances can use self.attributes.vncmode
as a shared mutable value.
Upvotes: 1