1

First, here's my example code:

EDIT: I should have specified, in my real code, that_func() is already returning another value, so I want it to return one value, and change c in addition

EDIT 2: Code edited to show what I mean

def this_func():
    c=1   # I want to change this c
    d=that_func()
    print(c, d)

def that_func():
     this_func.c=2 #Into this c, from this function
     return(1000) #that_func should also return a value

this_func()

What I want to do is change the local variable c in this_func() to the value I assign it in that_func(), so that it prints 2 instead of 1.

From what I've gathered online, this_func.c=2 should do just that, but it doesn't work. Am I doing something wrong, or have I misunderstood?

Thanks for any and all help.

1
  • this_func is a function, not a class. c is a local variable to that function - if it were a class instead, it would work like your question suggests. But that requires some changes to how you are doing things.. Commented Oct 6, 2015 at 19:51

2 Answers 2

1

Yes, you misunderstood.

functions are not class. You can't access variables of a function like that.

Obviously, it's not the smartest of code that can be written, but this code should give an idea about how to use variables of a function.

def this_func():
    c=1   # I want to change this c
    c=that_func(c) # pass c as parameter and receive return value in c later
    print(c)

def that_func(b): # receiving value of c from  this_func()
    b=2  # manipulating the value
    return b #returning back to this_func()

this_func()
Sign up to request clarification or add additional context in comments.

2 Comments

I'm sorry, I should have specified, in my real code, that_func() is already returning another value, so I want it to return one value, and change c in addition. I have edited the question.
You can always return more than one value and unpack them later. Is it ok?
0

Wrap it in an object and pass it to that_func:

def this_func():
    vars = {'c': 1}
    d = that_func(vars)
    print vars['c'], d

def that_func(vars):
    vars['c'] = 2
    return 1000

Alternatively, you can pass it in as a regular variable and that_func can return multiple values:

def this_func():
    c = 1
    c, d = that_func(c)
    print c, d

def that_func(c):
    c = 2
    return c, 1000

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.