Create objects under if __name__ == "__main__"
Write a Python class and create its object inside the if __name__ == "__main__": block.
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())Hello, SQA Tools
Line by line
Another file can import Greeter without creating this demo object.
Learn the concept
New to this topic? Read the lesson, then come back.