Why is the program not printing three lines?

Souvik Dutta souvik.viksou at gmail.com
Thu Mar 19 09:58:07 EDT 2020


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"
(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

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

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

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]
> --
> https://mail.python.org/mailman/listinfo/python-list
>


More information about the Python-list mailing list