Python Practice › OOP Programs › Program 8

Create objects under if __name__ == "__main__"

EasyOOP Programs · 8 of 48

Write a Python class and create its object inside the if __name__ == "__main__": block.

Advertisement
Output
Hello, SQA Tools

Approach

  1. Code in that block runs only when the file is executed directly, not when imported.

Solution

Python
class Greeter:    def __init__(self, name):        self.name = name     def greet(self):        return f"Hello, {self.name}"  if __name__ == "__main__":    g = Greeter("SQA Tools")    print(g.greet())
Output
Hello, SQA Tools

Line by line

Lines 9-11

Another file can import Greeter without creating this demo object.

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

Leave a Comment