在导入文件中使用主文件的变量
我正在使用 python,无法自己解决问题。我在下面的“主文件”中定义了变量(rb.data)。我导入了“hp 文件”来使用电炉功能。 (i611Robot、Teachdata、MotionParam、Position 包含在“A 文件”中)
from hp import *
from A import *
def main():
rb = i611Robot()
data = Teachdata()
m1 = MotionParam(30,20,10,2,2)
position_1 = Position(100,200,100,0,0,0)
...
....
hotplate(rb)
if __name__ == '__main__':
main()
这就是导入的“hp 文件”。
from A import *
def hotplate(rb) :
rb.motionparam( m1 )
rb.move( position_1 )
.......
但问题是,当我播放“主文件”时,它说
File "main.py" line.., in <module>
main()
File "main/py", line ...., in main
hotplate()
File ".../hotplate.py", in line .., in hotplate
rb.motionparam( m1 )
NameError : global name 'm1' is not defined
我已经问过有关如何在 hotplate.py 中使用 rb 的问题,并得到答案,我必须将 rb 放入 hotplate() 中。这效果很好。 但另一个问题是变量太多,比如rb和m1这样的参数, 将在 hotplate.py 文件中使用的position_1。 如何使用 hotplate.py 文件中的所有变量、实例、参数。
I am using python and cannot solve the problem myself. I defined the variables(rb. data) in the 'main file' below. And I imported 'hp file' to use hotplate function. ( i611Robot, Teachdata, MotionParam,Position are included in 'A file' )
from hp import *
from A import *
def main():
rb = i611Robot()
data = Teachdata()
m1 = MotionParam(30,20,10,2,2)
position_1 = Position(100,200,100,0,0,0)
...
....
hotplate(rb)
if __name__ == '__main__':
main()
And this is the 'hp file' which is imported.
from A import *
def hotplate(rb) :
rb.motionparam( m1 )
rb.move( position_1 )
.......
But the problem is when I play 'main file', it says
File "main.py" line.., in <module>
main()
File "main/py", line ...., in main
hotplate()
File ".../hotplate.py", in line .., in hotplate
rb.motionparam( m1 )
NameError : global name 'm1' is not defined
I already asked question about how to use rb in hotplate.py and get answer that I have to put rb in hotplate(). This works well.
But another problem is that there are so many variables, parameters like rb and m1,
position_1 that will be used in hotplate.py file.
How can I use those all variables,instances,parameters in hotplate.py file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如@Barmar 已经评论的那样,函数应该从参数中获取信息。
您的代码
您所做的不起作用:
函数
b
不知道变量myVar
,该变量超出范围。解决方案
您要做的就是将函数所需的参数传递给函数的参数:
输出
在此处了解 python 函数:https://www.w3schools.com/python/python_functions.asp
As @Barmar already commented, functions should get their information from parameters.
Your code
What you're doing doesn't work:
The function
b
doesn't know the variablemyVar
, the variable is out of scope.Solution
What you have to do is to pass the arguments which the function needs to the function's parameters:
Output
Learn about python functions here: https://www.w3schools.com/python/python_functions.asp