NB question on global/local variables in functions

Discussion in 'Python' started by Wolfgang, Jul 15, 2006.

  1. Wolfgang

    Wolfgang Guest

    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
     
    Wolfgang, Jul 15, 2006
    #1
    1. Advertising

  2. 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 ''.split('@')])"
     
    Bruno Desthuilliers, Jul 17, 2006
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. gamja
    Replies:
    4
    Views:
    313
    Christian Bau
    Sep 30, 2005
  2. Sullivan WxPyQtKinter
    Replies:
    10
    Views:
    670
    Antoon Pardon
    Nov 8, 2007
  3. Tim Rau

    global/local variables

    Tim Rau, Jan 24, 2008, in forum: Python
    Replies:
    8
    Views:
    456
    Tim Rau
    Jan 25, 2008
  4. danep2
    Replies:
    1
    Views:
    296
    Erik Wikström
    Apr 13, 2008
  5. king
    Replies:
    2
    Views:
    172
    Tad McClellan
    Jun 27, 2006
Loading...

Share This Page