Passing arguments to function - (The fundamentals are confusing me)

  • Thread starter =?ISO-8859-1?Q?Gregory_Pi=F1ero?=
  • Start date
D

Dennis Lee Bieber

So what if I do want to share a boolean variable like so:
<code>
sharedbool=True
class cls1:pass
cl=cls1()
cl.sharedbool1=sharedbool

sharedbool=False


True #but I wanted false!
</code>
Without the context for /why/ you want to share it, it is
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.
--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top