By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,766 Members | 1,401 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,766 IT Pros & Developers. It's quick & easy.

NB question on global/local variables in functions

P: n/a
Hi all,

I've started to write some functions but I have some problems with
common variables in that functions.

So I have some variables which should be accessible by all my functions
but not accessible by the rest of my code. How can I do this?

Thanks
Wolfgang

###function.py:

c1=123.0
c2=134.0

def fun(temp):
return temp+c1-c2

def fun1(temp):
return temp-c1
### caller.py
from function import *
print fun(10.0)
print c1

Jul 15 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Wolfgang wrote:
Hi all,

I've started to write some functions but I have some problems with
common variables in that functions.

So I have some variables which should be accessible by all my functions
but not accessible by the rest of my code. How can I do this?
You can use a closure:

def makefuns():
c1=123.0
c2=134.0

def fun(temp):
return temp+c1-c2
def fun1(temp):
return temp-c1

return fun, fun1

fun, fun1 = makefuns()

fun(42)
fun1(42)
But the canonical solution is to use a class:

class Foo(object):
def __init__(self):
self._c1=123.0
self._c2=134.0

def fun(self, temp):
return temp + self._c1 - self._c2

def fun1(self, temp):
return temp - self._c1

foo = Foo()
foo.fun(42)
foo.fun1(42)

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jul 17 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.