【问题标题】:'import' command, defining of variables'import' 命令,定义变量
【发布时间】:2014-09-17 06:26:44
【问题描述】:

我有一个名为 main.py 的程序,我在其中定义了几个变量 a、b、c 等,我还有一个程序说,xyz.py,我在其中编写了几个打印语句、函数、循环,等使用变量a,b,c等。来自 main.py。我在 main.py 中使用“import xyz”来调用 xyz.py。但它显示'name a,b,c等错误。 are not defined',这是可以理解的,因为我没有在 xyz.py 中定义这些变量。所以请告诉我如何在其他文件中使用变量。例如,如果我有类似以下的内容,

main.py

a=float(input('enter the value of a :: '))
b=float(input('enter the value of b :: '))
if a>1.0:
  import xyz
else:
  print 'exit'
print wxyz(a+b)
print abc(a+b)

xyz.py

print 'a is'+`a`
print 'b is'+`b`
def wxyz(a):
  return 2*a
def abc(b):
  return 4*b
print wxyz(a)
print abc(b)
while a>b:
  print a+b
  print wxyz(a*b)
  print abc(a*b)

【问题讨论】:

  • 查看python文档的module章节。

标签: python variables import


【解决方案1】:

这样做的明显方法是重组xyz.py,类似于:

def main(a, b):
    print 'a is {0!r}'.format(a) # backticks for repr are deprecated
    print 'b is {0!r}'.format(b)
    print wxyz(a)
    print abc(b)
    # ... etc. 

def wxyz(a):
  return 2 * a # whitespace per PEP-0008

def abc(b):
  return 4 * b

if __name__ = '__main__': # when script is run directly, not imported
    main(1, 2) # or whatever values 

现在导入脚本时不会直接运行任何内容,您仍然可以从main.py 调用xyz.main(a, b),显式传递值。

【讨论】:

    【解决方案2】:

    为了简单起见,我从您的 main.py 中删除了一些函数。我也执行了这些程序。 main.py 文件是:

     import xyz
    a=float(input('enter the value of a :: '))
    b=float(input('enter the value of b :: '))
    if a>1.0:
      import xyz
    else:
      print 'exit'
    

    你的 xyz.py 文件是:

    from main import a
    from main import b
    print 'a is',a
    print 'b is',b
    def wxyz(a):
      return 2*a
    def abc(b):
      return 4*b
    print wxyz(a)
    print abc(b)
    while a>b:
      print a+b 
    

    你得到的输出是:

    enter the value of a :: 12
    enter the value of b :: 12
    a is 12.0
    b is 12.0
    24.0
    48.0
    enter the value of a :: 0
    enter the value of b :: 0
    exit
    

    这就是你想要的我的朋友吗?

    【讨论】:

    • 你已经改进了代码。但我认为你遇到了我想避免的循环导入。
    • 你为什么要给导入别名与它们开头的名称相同?为什么不只是from main import a, b
    • 这显然是您的程序逻辑的另一个问题。我认为你的这个程序是“错误的”,不知道什么时候停止(没有条件退出程序)。但是我已经回答了您的错误问题(显示错误“未定义名称 a、b、c 等”)。我不是吗?
    • @jonrsharpe 对不起,我的错!是的,我们也可以这样做。我是 python 新手,还在学习,所以请原谅我。
    【解决方案3】:

    我想,你不想导入而是执行 py 代码?然后你必须使用 execfile 命令

    execfile( "xyz.py")
    

    但我明确推荐一种更面向对象的方法,在其中导入一个类,创建它的实例并访问它的值。

    【讨论】:

    • import 有效地执行了模块的代码,当然有一些不同,但一般from xyz import * 会导致类似的结果,应该首选。
    • 但是 execfile() 每次都会评估,不需要导入
    • 那更好吗?
    • Exec 无条件读取文件,不创建新模块。导入。
    • 我仍然认为这比导入更好。模块没有错,如果你需要重复执行代码,应该把它放到一个函数中。而且execfile每次都要读取文件,很费时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-10
    • 2013-02-15
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 2018-04-22
    相关资源
    最近更新 更多