【问题标题】:How can a function use variables generated by other (functions) as parameters for itself in python?一个函数如何在python中使用其他(函数)生成的变量作为自身的参数?
【发布时间】:2011-08-25 07:53:28
【问题描述】:

我正在学习 python,我想将我的代码的不同进程分成不同的函数。为此,我需要将先前函数的变量作为参数提供给另一个函数。我试过这样的事情

def F1 (A):
   B=A+1 

def F2 (B):
   C=B+1
   print C  

F1(1) F2()

例如,在这种情况下,我希望得到 3 作为最终结果。

但它不起作用。

【问题讨论】:

  • 什么不起作用——你期待什么?
  • catb.org/~esr/faqs/smart-questions.html#id479555(请阅读整篇文章)。我有一种“不起作用”的感觉,Python is 将您的代码.. 分离为函数命名空间。但你没有给出你所期待的线索。

标签: python function modular


【解决方案1】:

编辑:由于您已经编辑了您的帖子:在函数中创建的变量是该函数的本地变量,这意味着您不能在其他地方引用它们,除非您使用 global 命令,例如global myvar。不建议这样做,如果您的代码看起来像这样会更好:

def F1 (A):
  return A+1

def F2 (B):
 return B+1

first = F1(1)
second = F2(first)

print first, second

请记住,def F2 (B): 的意思是“使用 B 作为参数”——在您使用值调用函数之前,参数是未定义的。

---原始答案---

不知道你到底想在这里做什么,但让我试着解释一下函数:

def F1(A):
  ...

这将创建一个名为F1 的函数,它接受一个名为A 的参数。无论传递给F1 的参数都将设置为A,所以:

def F1(A):
  print A

F1('hello world')

在此代码中,F1 使用参数 'hello world' 调用。此参数设置为A,然后函数运行print A,现在等效于print 'hello world'

因此,在您的函数中,您会立即将 A 重新分配给 B,但尚未在代码中的任何位置创建 B。分配B=C 也没什么意义。

【讨论】:

  • 是的,你是对的。现在我修正了我想做的逻辑意义。
【解决方案2】:

return吧:

def F1 (A):
   return A+1

def F2 (B):
   C=B+1
   print C

# Then use it as parameter
F2(F1(1))

【讨论】:

    【解决方案3】:

    也许您需要一个共享对象来存储结果?类似dict:

    def f1(data):
        data['b'] = data['a'] + 1
    
    def f2(data):
        data['c'] = data['b'] + 1
        print data['c']
    
    my_data = {'a': 1}
    
    f1(my_data)
    f2(my_data) # prints 3
    

    【讨论】:

      猜你喜欢
      • 2018-08-15
      • 2013-11-25
      • 2021-07-10
      • 1970-01-01
      • 2019-03-11
      • 2019-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多