How to call a variable from one function inside another function?

时间:2016-04-25 08:50:02

标签: python

I have one function load

  def load():
        file = open((input("File name: ")), "r")
        movies_list = file.readlines()
        movies_list = [movie.strip() for movie in movies_list]
        file.close()

And I want to use the list movies_list in another function randomSelection

def randomSelection():
         print(random.choice(movies_list))

How can I get around this? Is there a way to declare movies_list as a global variable?

3 个答案:

答案 0 :(得分:8)

Return movies_list and pass it as an argument to randomSelection.

def load():
    with open((input("File name: ")), "r") as file:
        movies_list = file.readlines()
        movies_list = [movie.strip() for movie in movies_list]
    return movies_list

def randomSelection(movies_list):
     print(random.choice(movies_list))

movies_list = load()
randomSelection(movies_list)

答案 1 :(得分:1)

You can either return the movies_list and pass as arg to another function (or) use global variable

You can define a movie_list as a global variable as follows:

def load():
        file = open((input("File name: ")), "r")
        global movies_list
        movies_list = file.readlines()
        movies_list = [movie.strip() for movie in movies_list]
        file.close()

Then you can use the movies_list after the load() function is executed

load()
def randomSelection():
         print(random.choice(movies_list))

答案 2 :(得分:0)

Other answers are okay. Another option is defining your methods inside a class and using instance variable for sharing data between them:

class Test():
    def __init__(self):
        self.movie_list = "Empty"

    def f1(self):
        self.movie_list = "God_Father"

    def f2(self):
        print self.movie_list


test = Test()
test.f2()
test.f1()
test.f2()

Output:

>>> ================================ RESTART ================================
>>> 
Empty
God_Father
>>>