D
Dennis Lee Bieber
Without the context for /why/ you want to share it, it isSo what if I do want to share a boolean variable like so:
<code>
sharedbool=True
class cls1ass
cl=cls1()
cl.sharedbool1=sharedbool
sharedbool=False
True #but I wanted false!
</code>
difficult to guess...
Especially since, in your example, "cl.sharedbool1" is an
INSTANCE variable -- instance variables are, by definition, supposed to
be unique to each instance.
If you want /all/ instances of cls1 to share a variable, you
make it a class variable. If you just want the class to be able to
access something outside of itself, you might use "global" declarations.
If you're going that route, you might also want to define the
class to have the shared variable as a property, so retrieval and
setting correctly access the shared item.
-=-=-=-=-=-=-=-=
sharedBoolean = False
class Sharing(object):
def __init__(self):
pass
def _getSB(self):
global sharedBoolean
return sharedBoolean
def _setSB(self, nv):
global sharedBoolean
sharedBoolean = nv
return None
sharedBoolean = property(_getSB, _setSB)
s1 = Sharing()
s2 = Sharing()
print "Initial values"
print "sharedBoolean: ", sharedBoolean
print "s1: ", s1.sharedBoolean
print "s2: ", s2.sharedBoolean
sharedBoolean = True
print "Changed sharedBoolean itself"
print "sharedBoolean: ", sharedBoolean
print "s1: ", s1.sharedBoolean
print "s2: ", s2.sharedBoolean
s1.sharedBoolean = "Not a Boolean!"
print "Changed s1.sharedBoolean"
print "sharedBoolean: ", sharedBoolean
print "s1: ", s1.sharedBoolean
print "s2: ", s2.sharedBoolean
-=-=-=-=-=-=-=-=-=
Initial values
sharedBoolean: False
s1: False
s2: False
Changed sharedBoolean itself
sharedBoolean: True
s1: True
s2: True
Changed s1.sharedBoolean
sharedBoolean: Not a Boolean!
s1: Not a Boolean!
s2: Not a Boolean!
You could also use the property() mode to make instances access
a class variable (probably need to give it a different name), and not
need the global declarations.
--