Python: Can't use 2 files?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Daniel Johnson
    New Member
    • Dec 2011
    • 8

    Python: Can't use 2 files?

    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:
    Code:
    import test2
    
    a.test1()

    File 2:
    Code:
    class test:
        def test1(self):
            print "Test"
    
    a = test()
    These are obviously just tests but the error says name 'a' is not defined? Please help
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Object "a" is an attribute of test2. It can be accessed like this:
    Code:
    test2.a.test1()

    Comment

    • Smygis
      New Member
      • Jun 2007
      • 126

      #3
      the variable a is in the test2 namespace.

      try
      Code:
      test2.a.test1()
      or change
      Code:
      import test2
      # to:
      from test2 import *

      Comment

      • dwblas
        Recognized Expert Contributor
        • May 2008
        • 626

        #4
        You should really create an instance of the class in the first program
        Code:
        import test2
        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.
        Code:
        class test:
             def test1(self):
                 print "Test"
         
        ## the following won't be executed if you import this into another program
        if __name__ == "__main__":
            a = test()

        Comment

        Working...