How to prevent the execution of a class without placing it behind the main function, i need the class for execution of program. I want to use the class only after it is declared.
Code sample:
class Hello:
print('this message should not have been displayed')
def main():
print('hello world')
main()
Output:
this message should not have been displayed
hello world
As we can read in Python Documentation, "a class definition is an executable statement" so if you write print("string")
directly, you'll see the string in your output.
If you want to use a class to print a string, you have to create a method in the new Class, like this:
class Hello:
def helloPrint():
print('this message should not have been displayed')
def main():
print('hello world')
main()
Now your output will be:
hello world
You can print the Hello class message by writing the following lines at the end of the previous code:
h = Hello()
h.helloPrint()