Why is the program not printing three lines?

Chris Angelico rosuav at gmail.com
Wed Mar 18 21:36:00 EDT 2020


On Thu, Mar 19, 2020 at 12:30 PM Souvik Dutta <souvik.viksou at gmail.com> wrote:
>
> Hi,
> I wrote a purposeless code today.
> <code>
> class first():
>     print("From first")
>     def second():
>         print("From second")
> first()
> first.second()
> </code>
>
> Now the output I get is
> From first
> From second
>
> But when I comment the call of first that is the comment the second last
> line of the code (#first()).
> I get the same output. This is confusing because first() when called alone
> prints from first. And first.second() when called alone prints from first
> from second. But when both of them are called together, the output is from
> first from second. Should not first.second() print only from second. Or
> when I call both should I not get three line
> from first
> from first
> from second
> Why do I get that output?

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.

ChrisA


More information about the Python-list mailing list