Python:不能使用2个文件?

嗨,我一直在试着从一本书《艰难地学习python》中学习python,我正在试着学习如何在两个不同的文件中同时使用代码。我不能让它工作,这就是我正在做的。
文件1:

选择 | 换行 | 行号
  1. import test2
  2.  
  3. a.test1()

文件2:

选择 | 换行 | 行号
  1. class test:
  2.     def test1(self):
  3.         print "Test"
  4.  
  5. a = test()
  6.  

这些显然只是测试,但错误显示名称'a'未定义?请帮帮忙

# 回答1


对象"a"是的属性
测试2
。可以按如下方式访问:

选择 | 换行 | 行号
  1. test2.a.test1()
# 回答2


变量a位于Test2命名空间中。
试试看

选择 | 换行 | 行号
  1. test2.a.test1()

或改变

选择 | 换行 | 行号
  1. import test2
  2. # to:
  3. from test2 import *
# 回答3


您确实应该在第一个程序中创建类的实例

选择 | 换行 | 行号
  1. import test2
  2. a = test2.test() 

此外,在程序中使用__main__if语句,其代码应仅在程序本身调用时才执行。

选择 | 换行 | 行号
  1. class test:
  2.      def test1(self):
  3.          print "Test"
  4.  
  5. ## the following won't be executed if you import this into another program
  6. if __name__ == "__main__":
  7.     a = test() 

标签: python

添加新评论