我有两个python文件first.py和second.py
first.py看起来像
def main():
#some computation
first_variable=computation_resultsecond.py看起来像
import first
def main():
b=getattr(first, first_variable)
#computation但是我得到了No Attribute错误。有没有办法通过second.py访问first.py的main()方法中的变量?
发布于 2016-10-16 22:11:17
您应该使用函数调用和返回值,而不是这样。
从第一个文件中的函数返回computation_result,然后将结果存储在第二个文件的b变量中。
first.py
def main():
# computation
return computation_resultsecond.py
import first
def main():
b = first.main()另一种选择是在第一个文件中使用全局变量,您将在其中存储值并在以后引用它。
发布于 2016-10-16 22:18:23
您需要阅读教程中的9.1 and 9.2和语言参考中的Naming and Binding。
在你的例子中,first_variable只存在于first.main()的本地作用域中--当它执行的时候。它不能被该作用域之外的任何东西访问。
您需要将first_variable放入first的全局作用域中-然后在second中,您可以将其与first.first_variable一起使用。
一种方法是从first.main()返回一些内容并将其分配给first_variable。
def main():
return 2
first_variable = main()然后在second中,你可以使用它:
import first
times_3 = first.first_variable * 3https://stackoverflow.com/questions/40071150
复制相似问题