syam
syam

Reputation: 397

Parent class init is executing during inheritence

One basic question in OOP.

test.py file content:

class test(object):
    def __init__(self):
        print 'INIT of test class'

obj = test()

Then I opened another file.

I just inherited from the above test class:

from test import  test

class test1(test):
    def __init__(self):
        pass

So when I run this second file, the __init__() from the parent class is executed (the INIT got printed).

I read that I can avoid it by using

if __name__ == '__main__':
    # ...

I can overcome this, but my question is why the parent class's init is executing as I am just importing this class only in my second file. Why is the object creation code executed?

Upvotes: 0

Views: 36

Answers (1)

Mike Müller
Mike Müller

Reputation: 85442

Importing a module executes all module-level statements, including obj=test(). To avoid this, make an instance only when run as the main program, not when imported:

class test(object):
    def __init__(self):
        print 'INIT of test class'

if __name__ == '__main__':
     obj=test()

The problem is not the inheritance but the import. In your case you execute obj=test() when importing:

from test import test

When you import test, its name __name__ is test. But when you run your program on the command line as main program with python test.py, its name is __main__. So, in the import case, you skip obj=test()if you use:

if __name__ == '__main__':
     obj=test()

Upvotes: 5

Related Questions