【问题标题】:Using name of strings in different functions在不同的函数中使用字符串的名称
【发布时间】:2015-07-11 23:12:25
【问题描述】:

我需要在第二个函数的第一个函数中使用movies_list。我该怎么做?

def movie():
    movies_list = [movie.strip() for movie in movies_list]
    movie_explorer()

def rand():
    rand_item = print(random.choice(movies_list))

【问题讨论】:

  • 为什么不让它成为一个功能呢? movie 不接受变量。
  • 糟糕的例子,因为即使movie 也不起作用。尝试调用它,你会看到。

标签: python string function


【解决方案1】:

使用return 和参数

def movie():
    movies_list = [movie.strip() for movie in movies_list]
    movie_explorer()
    return movies_list

def rand(movies_list):
    rand_item = print(random.choice(movies_list))

并且在调用rand时记得调用函数为

rand(movie())

坏人

添加一行

global movies_list

作为两个函数的第一行

还有丑人

您可以使用可用的globals 对象。 (在此处添加完成押韵)

def movie():
    global movie_returns
    movie_returns = [movie.strip() for movie in movies_list]
    movie_explorer()
    # No return

def rand():  # No argument
    movies_list = next((globals()[v] for v in globals() if v=='movies_return'))
    rand_item = random.choice(movies_list)

【讨论】:

    【解决方案2】:

    让第二个函数嵌套在第一个函数上,这里有一个例子:

    def hello():
        a = "hello"
        def world():
            return "%s world" % a
        return world()
    print hello()
    

    【讨论】:

      【解决方案3】:

      将这两个函数放在一个类中,并使movies_list成为一个类变量。

      【讨论】:

      • 为什么要上课?那太复杂了。
      • 类有什么复杂的?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-23
      • 2016-06-02
      • 1970-01-01
      • 2014-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多