【问题标题】:Using a the same variable inside functions outside a function - Dronekit - OpenCV [closed]在函数外部的函数内部使用相同的变量 - Dronekit - OpenCV [关闭]
【发布时间】:2021-07-13 14:35:42
【问题描述】:

enter image description here

如何使用我在主代码函数内部定义的“red_position”变量?

【问题讨论】:

  • 请勿发布代码图片。请将您的代码以文本形式(在代码块中)复制并粘贴到此处,以便其他人可以更轻松地帮助您。

标签: python opencv


【解决方案1】:

您可以在函数外部使用全局变量,并在调用函数时为其赋值。

你的函数也可以返回类似的值

return red_position

并像这样使用 returned_value = colour_detection()

【讨论】:

  • 使用全局并不好,会导致各种问题。使用返回值,调用者将结果存储在本地(非glkobal)变量中
【解决方案2】:

你可以像这样在函数中使用 global 关键字:

red_position = None

def yourfunction():
   your fucntion body 
   if ():
      global red_position # inside a if statement like in your code annd use it whereever you like
     

变量在 if 语句中,因此不能在函数外部访问,所以在 if 语句之外声明变量。就这些

【讨论】:

  • 使用全局并不好,会导致各种问题。使用返回值,调用者将结果存储在本地(非glkobal)变量中
猜你喜欢
  • 2012-08-18
  • 2019-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-10
  • 1970-01-01
  • 2013-06-23
  • 2021-08-20
相关资源
最近更新 更多