Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > NB question on global/local variables in functions

Reply
Thread Tools

NB question on global/local variables in functions

 
 
Wolfgang
Guest
Posts: n/a
 
      07-15-2006
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

 
Reply With Quote
 
 
 
 
Bruno Desthuilliers
Guest
Posts: n/a
 
      07-17-2006
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 '(E-Mail Removed)'.split('@')])"
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Put variables into member variables or function variables? tjumail@gmail.com C++ 9 03-23-2008 04:03 PM
newbie question about scope, variables, declarations of variables and option strict (as in perl) Talha Oktay Ruby 8 03-08-2006 04:11 PM
question about class variables and instance variables Eric D. Ruby 3 02-01-2006 07:57 PM
Using explicitly sized variables in functions as auto variables or parameters Adel C Programming 3 03-17-2005 04:36 AM
please help me in distinguish redefining functions, overloading functions and overriding functions. Xiangliang Meng C++ 1 06-21-2004 03:11 AM



Advertisments