[英]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.