8. Problem to write Python class under the given syntax

In this Python oops program, we will write python class under syntax if __name__ == ‘__main__’. The program demonstrates the usage of a class with a constructor and a method. It creates an object, initializes its name attribute, and displays the name using the display_name method. The code is enclosed in an if __name__ == '__main__': block to ensure it only runs when the script is executed directly.

Write Python class under given syntax

Steps to solve the program
  1. The code demonstrates the use of the __name__ variable in Python, which provides information about the current module’s name.
  2. By using the if __name__ == ‘__main__’: condition, we can ensure that certain code within the block is executed only when the module is run directly as the main program.
  3. In this case, the MyClass class is defined, and an object obj is created with the name “Jason” passed as an argument to the constructor.
  4. The display_name method is then called on the obj object, which prints the name stored in the instance variable self.name.
  5. The use of if __name__ == ‘__main__’: is a common practice in Python to separate code that should only run when the module is run as the main program from code that should not be executed when the module is imported as a module in another program.

				
					class MyClass:
    def __init__(self, name):
        self.name = name
    
    def display_name(self):
        print("Name:", self.name)

if __name__ == '__main__':
    obj = MyClass("Jason")
    obj.display_name()
				
			

Output:

				
					Name: Jason
				
			

Related Articles

Python Class to get the class name and module name.

Python class with Single Inheritance.

Leave a Comment