0

I don't quite understand the usage of classes and import. I have two files as follows:

file test1.py contains the following:

class myClass:
    def __init__(self):
        pass # do nothing
    def update(self):
        print("test1")
        return

# test this module
m = myClass()
m.update()

file test2.py contains the following:

from test1 import myClass
m = myClass()
m.update()

when I run the module test2.py, it prints the following two lines of text:

test1
test1

Why does it print "test1" two times? I only want to use the class myClass. I don't want test2.py to execute the test program that is in test1.py.

ear1
  • 45
  • 5
  • 2
    Python has to execute all the code in the file when you import it. It's not clear why you have that "test code" at the end (if the test worked once you can surely remove it), but if you need it to run when running `test1.py` directly, put the bottom bit in an `if __name__ == '__main__':` block. – Robin Zigmond Mar 22 '21 at 21:15
  • 1
    When you import a module, all the top-level code in that module is executed. The `m = myClass()` and `m.update()` statements are at the top level, so they are executed. – John Gordon Mar 22 '21 at 21:15
  • Thanks. The information did a great job of explaining my observations, and fixed the issue. – ear1 Mar 23 '21 at 00:53

0 Answers0