【问题标题】:How can i use the result of one function, as an argument of another function?如何使用一个函数的结果作为另一个函数的参数?
【发布时间】:2018-06-30 05:35:09
【问题描述】:

它有点像这样。它只是主要代码的一个块。 x, y 定义正确

def  Function_1 (x,y):
    global zone
    # there are some conditions which get the value of variable zone
    return zone

def Function_2 (zone):
    #then there are some conditions wherein i use variable zone

Function_2 (zone)

所以错误是第 32 行中的“未定义区域” 很抱歉问了一个愚蠢的问题,但我是新手,我非常需要帮助

【问题讨论】:

  • @cᴏʟᴅsᴘᴇᴇᴅ 为什么你认为这不是代码
  • 在你修复它之前它不是代码。
  • @cᴏʟᴅsᴘᴇᴇᴅ 抱歉打扰了,但请您帮帮我
  • 仔细检查第 32 行发生了什么 - 错误消息表明您在分配区域之前正在使用它。

标签: python function variables arguments global


【解决方案1】:

这很正常!首先,您需要先分配变量才能使用它。 global zone 行允许 python 知道 zone 变量存在并且没有在函数中创建局部变量。如果缺少global 这个词,python 会创建另一个同名但地址不同的变量(本地)。

zone = None
def  Function_1 (x,y):
  global zone
  #there are some conditions which get the value of variable zone
  return zone

def Function_2 (zone):
  #then there are some conditions wherein i use variable zone

Function_2 (zone)

在查看您的代码时,我们看到名为 Function_1 的函数返回区域。

  • 有必要使用zone 作为全局变量吗?
  • 您可以像 Function_2 的参数一样重复使用结果 Function_1。像这样的东西:Function_2 (Function_1 (x,y))。

【讨论】:

    【解决方案2】:

    您正在尝试运行Function_2,而Function_1 尚未被调用。解决此问题的最简单方法是在 Function_1 的结果上运行 Function_2,如下所示:

    def  Function_1 (x,y):
        global zone
        #there are some conditions which get the value of variable zone
        return zone
    def Function_2 (zone):
        #then there are some conditions wherein i use variable zone
    Function_2(Function_1(1,2))
    

    当您调用Function_1(1,2) 时,Function_1(1,2) 变得等于函数返回的值,因此您只需将zone(Function_2 的参数)设置为Function_1(1,2) 的返回值。

    另外,你说x,y是定义的。不能设置变量的值和函数一起使用,需要传入。例如:

    x=1
    def Function (x):
        return x
    Function()
    

    这不起作用,您需要在这样调用时传入x:

    def Function (x):
        return x
    Function(1)
    

    这会将x 设置为1

    您似乎不太了解函数的工作原理,请尝试阅读 this 指南。

    【讨论】:

      猜你喜欢
      • 2018-11-13
      • 1970-01-01
      • 2020-03-14
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 2020-03-09
      相关资源
      最近更新 更多