Python Practice › OOP Programs › Program 8
Create objects under if __name__ == "__main__"
Write a Python class and create its object inside the if __name__ == "__main__": block.
Output
Hello, SQA Tools
Approach
- Code in that block runs only when the file is executed directly, not when imported.
Solution
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.