在python中从不同模块调用函数
我正在写一个用西班牙语修饰动词的基本程序。我目前有两个文件:main.py和test.py。我正在使用test.py测试函数。在python中从不同模块调用函数,python,function,import,module,Python,Function,Import,Module,我正在写一个用西班牙语修饰动词的基本程序。我目前有两个文件:main.py和test.py。我正在使用test.py测试函数。 目前main.py有: import test as present print("Welcome to Spanish Verb Conjugator") verb = raw_input("Enter the verb: ") length = len(verb) #print(length) v1 = length - 2 r1 = length - 1 v
目前main.py有:
import test as present
print("Welcome to Spanish Verb Conjugator")
verb = raw_input("Enter the verb: ")
length = len(verb)
#print(length)
v1 = length - 2
r1 = length - 1
v = verb[v1]
r = verb[r1]
end = str(v+r)
stem = verb[0:v1]
tense = raw_input("Choose your tense: ")
if tense == "present":
test.testt(end)
最后,我尝试调用test.py上的testt函数
test.py具有:
import main
def testt(ending):
if ending == "ar":
form = raw_input("Form: ")
if form == "yo":
return form + " " + stem + "o"
我的错误是:
Traceback (most recent call last):
File "/home/ubuntu/workspace/main.py", line 1, in <module>
import test
File "/home/ubuntu/workspace/test.py", line 1, in <module>
import main
File "/home/ubuntu/workspace/main.py", line 19, in <module>
test.testt(end)
AttributeError: 'module' object has no attribute 'testt'
回溯(最近一次呼叫最后一次):
文件“/home/ubuntu/workspace/main.py”,第1行,在
导入测试
文件“/home/ubuntu/workspace/test.py”,第1行,在
进口干管
文件“/home/ubuntu/workspace/main.py”,第19行,在
test.testt(结束)
AttributeError:“模块”对象没有属性“testt”
我正在使用python 2。将main.py中的代码更改为:
import test
print("Welcome to Spanish Verb Conjugator")
verb = raw_input("Enter the verb: ")
length = len(verb)
#print(length)
v1 = length - 2
r1 = length - 1
v = verb[v1]
r = verb[r1]
end = str(v+r)
print end
stem = verb[0:v1]
tense = raw_input("Choose your tense: ")
if tense == "present":
test.testt(end)
并将test.py更改为:
def testt(ending):
if ending == "ar":
form = raw_input("Form: ")
if form == "yo":
return form + " " + stem + "o"
此外
stem
在test.py
中不起作用,因为它在main.py
中有定义,您正在导入test
作为当前的。不要使用test.testt()
而是使用present.testt()
。此外,您的代码存在循环导入
问题 为什么test
要导入main
?看起来您没有向我们展示您的所有代码,或者不是最新版本。您编写了import test as present
,因此当您运行该代码时,错误应该是test
未定义。stem
在test.py
中无法工作,因为它是在main.py
中定义的。如何使stem在test.py中工作?与end
工作的方式相同,只需将其作为参数传递给test.testt(end,stem)
并将test.py
更新为def testt(end,stem)