PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 11, 2022

[FIXED] How to make classes not run without being called?

 July 11, 2022     class, message, printing, python, windows     No comments   

Issue

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

Solution

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


Answered By - Calaf
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing