How to Pass Variables Across Functions

How do I pass variables across functions?

This is what is actually happening:

global_list = []

def defineAList():
local_list = ['1','2','3']
print "For checking purposes: in defineAList, list is", local_list
return local_list

def useTheList(passed_list):
print "For checking purposes: in useTheList, list is", passed_list

def main():
# returned list is ignored
returned_list = defineAList()

# passed_list inside useTheList is set to global_list
useTheList(global_list)

main()

This is what you want:

def defineAList():
local_list = ['1','2','3']
print "For checking purposes: in defineAList, list is", local_list
return local_list

def useTheList(passed_list):
print "For checking purposes: in useTheList, list is", passed_list

def main():
# returned list is ignored
returned_list = defineAList()

# passed_list inside useTheList is set to what is returned from defineAList
useTheList(returned_list)

main()

You can even skip the temporary returned_list and pass the returned value directly to useTheList:

def main():
# passed_list inside useTheList is set to what is returned from defineAList
useTheList(defineAList())

How should I pass variables between functions in this class?

  • You're getting confused between classes and instances, and between class attributes and instance attributes. (Read e.g. this)

    • The OO way to store state variables (like x,y) so you don't have to pass them around between function(/method) calls is to make them instance attributes. (Not class attributes, as you were doing. Don't worry, I did that too when I first learned Python).
    • So we declare a class UI; we will access its instance attributes as self.x, self.y inside its methods.
    • Don't try to directly do stuff on class UI. You must instantiate it first: ui = UI(). You should follow the Python convention that class names are Uppercase/CamelCase: UI, instance names are lowercase e.g. ui, ui1, ui2...
    • You were trying to put code directly into the class definition of UI, not define methods and put the code in that, and your UI class didn't even have an __init__()
    • Methods are functions inside a class, they always have a first argument self. If they didn't, the method wouldn't be able to access the rest of the class(!)
  • Now that we cleared that up, there are a couple of ways to decompose the methods to do what you want to do:

    1. Have an empty __init__() (you could just make its body do pass). Have get_numbers() and check_numbers() be separate methods, which you manually call in-order. This is what I show below and is closest to what you said you want ("I want no reference to any function inside another function"), but is bad decomposition - what if the client called check_numbers() before get_numbers()? It would blow up on TypeError since __init__() initializes x,y with None.
    2. Better would be to have __init__() call the method get_numbers() under-the-hood to guarantee the instance gets properly initialized. (We could always call get_numbers() again later if we want to input new numbers). That's easy to change, I leave that to you.
    3. In approach 1., we had to initialize the instance members to something (otherwise trying to access them in check_numbers() will blow up). So we initialize to None, which will deliberately throw an exception if we compare. It doesn't really matter, this is just bad decomposition to not have __init__() properly initialize the instance (and call whatever methods it needs to to get that done). That's why approach 2. is better. Generally you should always have an __init__() that initializes the class into a known state, so that any other method can safely be called.

Code:

class UI:
def __init__(self, x=None, y=None):
self.x = x
self.y = y
def get_numbers(self):
self.x = input("Enter the X number: ")
self.y = input("Enter the Y number: ")
def check_numbers(self):
"""This is bad decomposition because if the client calls check_numbers() before get_numbers(), the NoneType will throw a TypeError"""
if self.x > self.y:
print(f'x is larger then y: x is {self.x} and y is {self.y}')
elif self.y > self.x:
print(f'y is larger then x: x is {self.x} and y is {self.y}')
elif self.y == self.x:
print(f'x is equal to y: x is {self.x} and y is {self.y}')
else:
print("Don't know mate")

# Declare an instance and reuse it three times
ui = UI()
for n in range(3):
ui.get_numbers()
ui.check_numbers()

Also, some minor stylistic points:

  • you don't need a while-loop for a simple counter: n = 0, while(n < 3) ... n += 1 . A for-loop is a one-liner: for n in range(3):
  • good Python style (see PEP-8) is to name the methods lower_case_with_underscores, thus get_numbers(), check_numbers()
  • a great top-down way to design a class is to write its method signatures first, think about what methods and attributes you'll need and how they'll work together. Example: "get_numbers() will get the user input, hence we'll need attributes self.x,y to store the numbers so check_numbers() can access them". And this way you should hit any problems with class design before you've written a wall of code.

How can I share a variable between functions in Python?

Object-oriented programming helps here:

class MyClass(object):
def __init__(self):
self.a = ['A','X','R','N','L'] # Shared instance member :D

def fun1(self, string):
out = []
for letter in self.a:
out.append(string+letter)
return out

def fun2(self, number):
out = []
for letter in self.a:
out.append(str(number)+letter)
return out

a = MyClass()
x = a.fun1('Hello ')
y = a.fun2(2)

Passing variables between functions in Python

Think of it as passing objects around by using variables and function parameters as references to those objects. When I updated your example, I also changed the names of the variables so that it is clear that the objects live in different variables in different namespaces.

def funa():
name=input("what is your name?")
age=input("how old are you?")
return name, age # return objects in name, age

my_name, my_age = funa() # store returned name, age objects
# in global variables

def funb(some_name, some_age): # a function that takes name and
# age objects
print(some_name)
print(some_age)

funb(my_name, my_age) # use the name, age objects in the
# global variables to call the function

How to share a variable between two functions in C?

you pass the variable to both functions.... in general functions shouldn't hold state.

quickly you find passing variables is not so nice and becomes fragile, so instead, you pass structs.... then functions start working on the state of structs.

typedef struct 
{
int var1;
} blah_t;

void foo1(blah_t* b)
{
b->var1=0;
}

void foo2(blah_t* b)
{
b->var1++;
}

this is the very simplistic seed idea behind doing OO C.

Pass Variables Between Functions Returning Templates

if you're not retrieving the list from something more permanent (such as a database) you might want to make a third function where you declare/define your list and then call that function..

def my_list():
make_a_list = [1, 2, 3] # make/get list however you want
return make_a_list

@app.route('/')
def home():
list1 = my_list()
print('list 1 = ', list1) # do stuff with list
return render_template('template1.html', list1=list1)

@app.route('/test')
def test():
list2 = my_list()
print('list 2 = ', list2) # do stuff with list
return render_template('template2.html', list2=list2)

i'm not sure how or where you're getting your list, but this will avoid defining a global.

can someone please explain me how to pass variables between 2 functions using python 3?

ok i just solved by myself:

from tkinter import *
w1=Tk()
w2=Tk()
w2.withdraw()
def main(which):
w2.deiconify()
def go(which):
print(which)
b=Button(w2,text='print',command=lambda:go(which))
b.pack()
b1=Button(w1,text='button 1',command=lambda:main('button 1'))
b1.pack()
b2=Button(w1,text='button 2',command=lambda:main('button 2'))
b2.pack()
w1.mainloop()

How do I pass variables between functions in Javascript?

You need to either pass it between them, or it seems from your example, just declare it in a higher scope:

var str;
function a(){
str="first";
}
function b(){
var something = str +" second"; //new is reserved, use another variable name
}


Related Topics



Leave a reply



Submit