How to make classes not run without being called?

Viewed 762

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
3 Answers

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

Ok, so while "a class definition is an executable statement", not all class statements need to be directly inside a module. There is also this pattern:

def create():
    class foo:
        a = 1
        print('Inside foo')
    return foo

print('running')

C = create()

Output:

running
Inside foo

This delays the execution of foo to a particular time of your choosing.

You can't write it like this... you must place it inside a method to constructor like this one

class Hello():
    def __init__(self):
        print('this message should not have been displayed')


def main():
    print('hello world')


main()
hello = Hello()
Related