Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

python - how to call a function from another file?

Sorry basic question I'm sure but I can't seem to figure this out.

Say I have this program , the file is called pythonFunction.py:

def function():
   return 'hello world'

if __name__=='__main__':
   print function()

How can I call it in another program? I tried:

import pythonFunction as pythonFunction
print pythonFunction.function

Instead of 'hello world', I get ...I have done this in the past by making the first file a class, but I was wondering how to import the function correctly? If it helps, in my real file, I am printing a dictionary

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to print the result of calling the function, rather than the function itself:

print pythonFunction.function()

Additionally, rather than import pythonFunction as pythonFunction, you can omit the as clause:

import pythonFunction

If it's more convenient, you can also use from...import:

from pythonFunction import function
print function() # no need for pythonFunction.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...