Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best practice for passing values between functions in Python

What is pythonic best practice for allowing one function to use another function's returned values? e.g. Is it better to call one function within another, or better that function1 returns to the class, and class variables are assigned that are then used by function2? Secondly, how many different ways could you pass values between functions?

class adding:

    def get_values(self):
        x = input("input x")
        y = input("input y")
        z = input("input z")
        return x, y, z

    def use_values(self, x, y, z):
        print x+y+z

if name == 'main':
    dave = adding()
    x, y, z = dave.get_values()
    dave.use_values(x, y, z)

Or

    dave = adding()
    dave.use_values(*dave.get_values())
like image 823
zantzinger Avatar asked Jun 04 '11 09:06

zantzinger


People also ask

What are the two methods of passing arguments to functions in Python?

5 Types of Arguments in Python Function Definition:keyword arguments. positional arguments. arbitrary positional arguments.

How do you pass variables in Python?

If a Python newcomer wanted to know about passing by ref/val, then the takeaway from this answer is: 1- You can use the reference that a function receives as its arguments, to modify the 'outside' value of a variable, as long as you don't reassign the parameter to refer to a new object.

Do Python functions pass by reference or value?

In Python,Values are passed to function by object reference. if object is immutable(not modifiable) than the modified value is not available outside the function. if object is mutable (modifiable) than modified value is available outside the function.


1 Answers

As import this would say, "explicit is better than implicit"; so go with the first form.

If the number of return values becomes large, let use_value take a sequence argument instead.

like image 195
Fred Foo Avatar answered Oct 04 '22 20:10

Fred Foo