-2
class pyt():

    print(4)

pyt()
pyt()

is giving only one output 4. I think it should print two fours but since my intuition is not correct. I wanted to know why this program is printing only one 4.

  • 3
    Class level code is run only once at class initialization. You might want to have a constructor (`__init__`) to run code for every instance. – Klaus D. Jul 26 '20 at 02:38
  • Does this answer your question? [What is the purpose of class methods?](https://stackoverflow.com/questions/38238/what-is-the-purpose-of-class-methods) – NelsonGon Jul 26 '20 at 02:45
  • 2
    @NelsonGon no, this is nothing to do with class methods in Python. OP is either expecting code in the class body to be re-run for each instantiation, or perhaps has `class` confused with `def`. – Karl Knechtel Jul 26 '20 at 02:52
  • @KarlKnechtel Yes I will retract.I just thought that post would help them to understand the difference between classes and methods. – NelsonGon Jul 26 '20 at 02:54

4 Answers4

1

The reason the program only prints 4 once is because, the print() function is only called when you define the class:

class pyt():
    print(4)

Output:

4

When you call the class, the print() function won't initiate:

class pyt():
    print(4)

pyt()
pyt()
pyt()
pyt()
pyt()
pyt()

Output:

4
Red
  • 26,798
  • 7
  • 36
  • 58
1

You wanted to use def instead of a class

def pyt():

    print(4)

pyt()
pyt()

The output will be:

enter image description here

You can read more on a difference between def and class here

If you want to do it with the class keyword

class pyt():
    def __init__(self, value_to_print=4):
        self.value_to_print = value_to_print
        
    def print_value(self):
        print(self.value_to_print)
        

if __name__ == '__main__':
    pyt_obj = pyt()
    pyt_obj.print_value()
    pyt_obj.print_value()

The output will be the same.

Ahmet
  • 7,527
  • 3
  • 23
  • 47
0

This should be a function instead of a class if you want to be able to call your code out twice then you should do this instead:

    def pyt():
        print(4)
    pyt()
    pyt()

The result will be:

    4
    4
slvnml
  • 11
  • 3
0

If you really want to do it with a class,like:

class pyt():
    def __init__(self):
        print(1)

pyt()

You could get more information here about __init__.

Kevin Mayo
  • 1,089
  • 6
  • 19