Statements within Python Classes executed but class not called

So I was trying some debugging prints and what i noticed the print statements within the child class are being executed even though I never call the class. Can someone explain why???

Thanks.

class Parent (object):

    def override(self):
        print ("Parent oveerride()")


class Child (Parent):

    print ("Chlld enter  >>>>>>")
   
    def override(self):
        print ('Son overwride ()')

    print ("Chlld exit <<<<<<")


dad = Parent()
#son = Child()

dad.override() 
#son.override()

Output:

Chlld enter >>>>>>
Chlld exit <<<<<<
Parent oveerride()

Everything you have in a class is executed once when the module is loaded. That’s how the members are set up. Of course you usually don’t put function calls there.

Hello there, of course the inheritance of parent class in there in child class but in the child class function you make a indentation that is making it under the class so, I am posting the correction I found.so without calling the method you cannot print or call or method’s substance.

class Parent (object):

    def override(self):

        print ("Parent oveerride()")

class Child (Parent):

    print ("Chlld enter  >>>>>>")

   

    def override(self):

        print ('Son overwride ()')

        print ("Chlld exit <<<<<<")

I might be misunderstanding you, but this sentence, as I understand it, is fundamentally wrong.

In @jpctx’s code no methods of the child class are called. The reason why he’s seeing the print calls executed is because Python executes every statement, including function calls, in a class definition when it reads the module.

(If you put your sentence the other way around, it may be correct in some contexts, but even then you’d have to be very careful with your assumptions.)

Yes, Sorry about that statement. This sentence is completely wrong this must be. I am going to edit that.
for the child classes with the inherent parent class you will get the parent class properties.
and yes with calling the module python will execute everything once.
but there was an indentation that is making the sentence under the class so therefore printing it. Thank you @florian

1 Like

No need to apologize! We’re all learning. :slight_smile:

I just thought it would be good to correct this, because others might read the thread, and it was really quite the opposite to how inheritance works.

No worries :grin: :slightly_smiling_face:

A free service run by Zed A. Shaw for learncodethehardway.org.