简体   繁体   English

当我尝试在函数中使用脚本中的变量时出现错误

[英]Getting an error when I try to use a variable from my script in my function

I have a function: 我有一个功能:

def Hanoi(A):

    pegA=['disc0', 'disc1', 'disc2']

If I call the function 如果我调用该函数

Hanoi(pegA)

(I am using Autodesk Maya) (我正在使用Autodesk Maya)

I get this error: name 'pegA' is not defined 我收到此错误:未定义名称'pegA'

I was under the impression that you could use a variable from your script in a function? 我的印象是,您可以在函数中使用脚本中的变量? Can anyone explain to me why I am getting this error? 谁能向我解释为什么我会收到此错误?

Thank you 谢谢

pegA is defined in the function, but you are passing it as an argument to the function. pegA在函数中定义,但是您将其作为参数传递给函数。 Basically youre trying to call it before it has been defined 基本上,您尝试在定义之前调用它

With this code: 使用此代码:

def Hanoi(A):
    pegA=['disc0', 'disc1', 'disc2']

You've defined a function Hanoi , and when the function is run, a local variable pegA is created. 您已经定义了一个函数Hanoi ,当该函数运行时,将创建一个局部变量pegA When the function returns, pegA is destroyed because it's local 函数返回时, pegA被销毁,因为它是本地的

Then when you call the function: 然后,当您调用函数时:

Hanoi(pegA)

There's no pegA to pass into the function. 没有pegA可以传递该函数。 It'll get created inside, but doesn't exist outside. 它会在内部创建,但在外部不存在。


What you can do is create pegA outside the function, and pass it in: 您可以做的是在函数外部创建pegA ,并将其传递给:

def Hanoi(A):
    print A  # pegA was assigned to A when you called the function

pegA=['disc0', 'disc1', 'disc2']
Hanoi(pegA)

Lastly, as an aside, the general convention is to start functions with lowercase letters, reserving uppercase for class names. 最后,顺便说一句,通常的约定是以小写字母开头的函数,为类名保留大写字母。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我尝试从脚本中的 function 更改我的全局变量时,没有任何反应吗? - When I try to change my global variable from a function in my script nothing is happening? 使用传递给函数的字符串获取NameError,表示在尝试在函数中使用该字符串时未定义该字符串 - Getting a NameError with the string I pass in to a function, saying the string is not defined when I try to use it within my function 在我的脚本中尝试执行 exe 时出错 - Getting error when try to execute exe while of my script 当我尝试使用参数测试我的代码时,我正在努力从我的 function 中删除此错误 - I'm struggling to remove this error from my function, when I try to test my code with the parameters 当我尝试使用 pyautogui 运行代码时出现错误单击 function - Getting Error when I try to run my code with pyautogui click function 当我尝试使用我的网络摄像头(python)时出错 - Error when I try to use my webcam (python) 当我尝试启动 celery/supervisor 实例时出现“错误(生成错误)” - I'm getting an "ERROR (spawn error)" when I try to start my celery/supervisor instance 当我尝试在终端上运行代码时,我不断收到“ModuleNotFound”错误,即使我安装了它 - I keep getting "ModuleNotFound" error when i try to run code on my terminal even though i installed it 当我尝试调用我的函数时,为什么会出现 NameError? - Why am I getting a NameError when I try to call my function? 为什么使用.insert()函数时列表会越来越大? - Why are my lists getting bigger when I use .insert() function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM