Edit: As I just found out, “Singleton” isn’t that useful in python. python uses “Borg” instead. http://wiki.python.de/Das%20Borg%20Pattern With Borg I was able to read & write global variables from different classes like:
b1 = Borg()
b1.colour = "red"
b2 = Borg()
b2.colour
>>> 'red'
But I was not able to create/read a list with borg like:
b1 = Borg()
b1.colours = ["red", "green", "blue"]
b2 = Borg()
b2.colours[0]
Is this something Borg doesn’t support? If yes: How can I create global lists which I can read & write from different classes?
Original Question:
I want to read & write global variables from different classes. Pseudocode:
class myvariables():
x = 1
y = 2
class class1():
# receive x and y from class myvariables
x = x*100
y = y*10
# write x and y to class myvariables
class class2():
# is called *after* class1
# receive x and y from class myvariables
print x
print y
printresult should be “100” and “20”.
I’ve heard that “Singleton” can do this… but I didn’t found any good explanation of “Singleton”. How can I make this simple code work?
Borg pattern class attrs will not be reset on new instance calls, but instance attrs will be. Be sure that you are using class attrs instead of instance attrs if you want to preserve previously set values. The code below will do what you want.
To prove the point, try it again with the instance attr y. You will get an unhappy result.
good luck,
Mike