Reputation: 64064
I have the following Class and the corresponding method.
#!/usr/bin/env python
class Foo:
def __init__(self, x):
self.x = x
def bar(self):
bar_out = self.x + 5
return bar_out
def qux(self):
qux_out = bar_out + 3
return qux_out
def main():
"""docstring for main"""
f = Foo(5)
main_bar_out = f.bar()
print main_bar_out
#main_qux_out = f.qux()
#print main_qux_out
if __name__ == '__main__':
main()
What I want to do here is to make the method a=qux
takes the value from bar
, process it and return a value. So that the final output of main_qux_out
is 13. How can I do this correctly?
Note that here I want qux()
to take the value automatically from bar()
, without passing any parameter.
Update
Thanks for @thefourtheye, for the response. I have further questions.
Let say if I want to have bar()
to return two or more values (this can be string, string, list or dict), how can I call it from qux()
. I tried this but failed.
#!/usr/bin/env python
class Foo:
def __init__(self, x):
self.x = x
def bar(self):
self.bar1_out = self.x + 5
self.bar2_out = self.x + 1
return (self.bar1_out,self.bar2_out)
def qux(self):
self.qux_out1 = self.bar1_out() + 3
self.qux_out2 = self.bar2_out() + 6
return ( self.qux_out1, self.qux_out2)
def main():
"""docstring for main"""
f = Foo(5)
mbr_out1, mbr_out2 = f.bar()
print mbr_out1, "\t", mbr_out2
mqx_out1, mqx_out2 = f.qux()
print mqx_out1, "\t", mqx_out2
if __name__ == '__main__':
main()
This should print:
10 6
13 12
Upvotes: 1
Views: 61
Reputation: 239653
You cannot access a local variable defined in one function, from another function. But you can invoke the bar
function and use the return value like this
def qux(self):
return self.bar() + 3
If you want to decide which value to use (bar
or the value passed as parameter) dynamically, then you can do something like this
def qux(self, myvalue = None):
if myvalue is not None:
return myvalue + 3
else:
return self.bar() + 3
If you don't pass any value to qux
, myvalue
will be default take None
as its value. Inside the function, we check if it is not None
, then we use the value as it it, otherwise we call self.bar()
and use that value.
If you are planning to return two values from bar
, then you can unpack them like this
def qux(self, myvalue = None):
first, second = myvalue or self.bar()
return first + 3, second + 6
Here myvalue or self.bar()
makes sure that we take self.bar()
if myvalue
is None
.
Note: If you are planning to do this way, then you need pass two values for myvalue
as well, like this
self.qux((1, 2))
Upvotes: 3
Reputation: 71
methods inside of a class can only access variables of that class or variables defined inside the method. What you ought to do is either make bar a variable of the class (instead of being part of the method)
def bar(self):
self.bar_out = self.x + 5
return self.bar_out
or call bar() and use the output in the calculation
def qux(self):
qux_out = self.bar() + 3
Upvotes: 1