By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,667 Members | 1,352 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,667 IT Pros & Developers. It's quick & easy.

Python: Can't use 2 files?

P: 8
Hi, i have been trying to learn python from a book learn python the hard way and i am trying to learn how to use code in two different files simultaneously. I can't get it to work though, this is what i'm doing.

File 1:
Expand|Select|Wrap|Line Numbers
  1. import test2
  2.  
  3. a.test1()

File 2:
Expand|Select|Wrap|Line Numbers
  1. class test:
  2.     def test1(self):
  3.         print "Test"
  4.  
  5. a = test()
  6.  
These are obviously just tests but the error says name 'a' is not defined? Please help
Feb 10 '12 #1
Share this Question
Share on Google+
3 Replies

bvdet
Expert Mod 2.5K+
P: 2,851
Object "a" is an attribute of test2. It can be accessed like this:
Expand|Select|Wrap|Line Numbers
  1. test2.a.test1()
Feb 10 '12 #2

Smygis
100+
P: 126
the variable a is in the test2 namespace.

try
Expand|Select|Wrap|Line Numbers
  1. test2.a.test1()
or change
Expand|Select|Wrap|Line Numbers
  1. import test2
  2. # to:
  3. from test2 import *
Feb 10 '12 #3

Expert 100+
P: 626
You should really create an instance of the class in the first program
Expand|Select|Wrap|Line Numbers
  1. import test2
  2. a = test2.test() 
Also, use the __main__ if statement in programs with code that should only be executed if the program is called by itself.
Expand|Select|Wrap|Line Numbers
  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() 
Feb 10 '12 #4

Post your reply

Sign in to post your reply or Sign up for a free account.