Why is the program not printing three lines?

Pieter van Oostrum pieter-l at vanoostrum.org
Thu Mar 19 07:56:26 EDT 2020


Chris Angelico <rosuav at gmail.com> writes:

> Creating the class runs all the code in the class block, including
> function definitions, assignments, and in this case, a print call.
>
> Classes are not declarations. They are executable code.

Demo:

In [26]: class first():
     ...     print("From first")
     ...     def second():
     ...         print("From second")
>From first

You see, the print "From first" occurs at class definition time.

In [27]: first()
Out[27]: <__main__.first at 0x10275f880>

Calling the class (i.e. creating an instance) doesn't print anything,
because the print statement is not part of the class __init__ code.

In [28]: first.second()
>From second

That's expected.

In [29]: first.second()
>From second

Again.
-- 
Pieter van Oostrum
www: http://pieter.vanoostrum.org/
PGP key: [8DAE142BE17999C4]


More information about the Python-list mailing list