简体   繁体   中英

Referring a function from different python script

I am learning python from here. 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 . In this code I see him using 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 . In this, I defined a function that just prints something out. In another python script, say myScript.py what I do is

testScript.callFunction()

I get an error when I run myScript.py :

NameError: name 'testSCript' is not defined.

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. 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. In your myScript.py file, add this on top:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM