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.
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.
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
You wanted to use def
instead of a class
def pyt():
print(4)
pyt()
pyt()
The output will be:
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.
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
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__
.