Why is the program not printing three lines?

Pieter van Oostrum pieter-l at vanoostrum.org
Thu Mar 19 10:36:59 EDT 2020


Souvik Dutta <souvik.viksou at gmail.com> writes:

> I should have been more clear
> class first():
>     print("from first")
>     def second():
>         print("from second")
> first()
>
> When I run the above code the output is
> "from first"

And where do you think this comes from? Are you thinking this comes from
the call 'first()'?
If so, that is not correct. See my Demo below.
It is from the class definition.

Run only this code, and you will see it also print "from first":

class first():
    print("from first")
    def second():
        print("from second")

> (2ND CODE)
>
> class first():
>     print("from first")
>     def second():
>         print("from second")
> first.second()
>
> When I run this code the output is
> "from first"
> "from second"
>
> Thus going by the above logic

Which logic?

> class first():
>     print("from first")
>     def second():
>         print("from second")
> first()
> first.second()
>
> This should have given the following output
> from first
> from first
> from second

No, because this is not the combination of the first two codes. To have this combination, you should include the class definition twice.

> That is I should have got from first 2 times. But instead I got this output.
> from first
> from second
> Why is this so?

'From first' is the result of the class definition. 'from second' is the result of first.second().
And first() doesn't produce any output.

Your problem is probably that you think that the call first() executes all the statements in the class definition. It doesn't. That's not how Python class definitions work.

Check the Demo below another time.

> On Thu, Mar 19, 2020, 5:30 PM Pieter van Oostrum <pieter-l at vanoostrum.org>
> wrote:
>
>> 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