[英]Referring a function from different python script
I am learning python from here. 我正在从这里学习python 。 In this exercise what it says is to find out the errors in his code that is given in this particular location
在本练习中,它所说的是找出在这个特定位置给出的代码中的错误
Now in the previous exercise, number 25, he made us write a few defs
. 现在在上一次练习中,他已经写了几个
defs
。 In this code I see him using words = ex25.break_words(sentence)
. 在这段代码中,我看到他使用
words = ex25.break_words(sentence)
。 Now I am not sure if we can do this or not. 现在我不确定我们能否做到这一点。
So what I did was to create a new python script and name it testScript.py
. 所以我做的是创建一个新的python脚本并将其命名为
testScript.py
。 In this, I defined a function that just prints something out. 在这里,我定义了一个只打印出来的函数。 In another python script, say
myScript.py
what I do is 在另一个python脚本中,比如说
myScript.py
我做的是什么
testScript.callFunction()
I get an error when I run myScript.py
: 运行
myScript.py
时myScript.py
:
NameError: name 'testSCript' is not defined.
NameError:未定义名称'testSCript'。
But I do not get any such error when I am running the above code from the location given by the author. 但是当我从作者给出的位置运行上面的代码时,我没有得到任何这样的错误。 Also, in the
Common Questions By Student
section in the end in here. 此外,在最后的
Common Questions By Student
部分中。 I am not sure what is he talking about in the first question. 我不确定他在第一个问题中谈到了什么。 What exactly does he mean by removing the references.
删除引用的确切含义是什么?
Thanks 谢谢
You can import your testScript
given that the two files are in the same directory. 您可以导入
testScript
因为这两个文件位于同一目录中。 In your myScript.py
file, add this on top: 在
myScript.py
文件中,将其添加到顶部:
import testScript
Then you can do: 然后你可以这样做:
testScript.callFunction()
Alternatively, you could do it as (although I highly advise against this method): 或者,您可以这样做(虽然我强烈建议不要使用此方法):
from testScript import *
callFunction() #no need to write testScript. anymore
Alternatively, you could also do it as: 或者,您也可以这样做:
import testScript as ts
ts.callFunction()
And finally, you also have the option of doing (again, I'd stay away from this one as well): 最后,你也可以选择做(再次,我也远离这个):
from testScript import callFunction
callFunction()
Hope that helps. 希望有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.