杰瑞科技汇

Python if __name__ == __main__ 有何作用?

Of course! This is a fundamental and excellent question for anyone learning Python.

Let's break it down. The phrase if main()== is actually a slight misstatement of the most common and correct way to write it.

The correct and standard Python idiom is:

if __name__ == "__main__":

You'll often see code inside this block followed by a function call, like this:

def main():
    print("Hello, World!")
if __name__ == "__main__":
    main()

The Short Answer

The line if __name__ == "__main__": is a guardian or a gatekeeper for your script's code. It ensures that the code inside this block only runs when the script is executed directly and not when it's imported as a module into another script.


The Detailed Explanation: What is __name__?

To understand this, you need to know about a special built-in variable in Python called __name__.

  1. When you run a script directly: If you have a file named my_script.py and you run it from your terminal like this:

    python my_script.py

    ...Python automatically sets the __name__ variable inside that file to the string "__main__".

  2. When you import a script as a module: If you have another file, another_script.py, and you import my_script.py into it:

    # In another_script.py
    import my_script

    ...Python sets the __name__ variable inside my_script.py to the name of the module, which is the string "my_script".

The Comparison __name__ == "__main__"

Now, the if statement makes perfect sense:

  • When you run my_script.py directly:

    • __name__ is "__main__".
    • The condition if "__main__" == "__main__": is True.
    • The code inside the block is executed.
  • When you import my_script.py into another_script.py:

    • __name__ is "my_script".
    • The condition if "my_script" == "__main__": is False.
    • The code inside the block is skipped.

Why is this so important? (The "Why")

This is the key to writing reusable and professional Python code. It separates the code that defines your functions and classes from the code that uses them.

Example: A Reusable Module

Let's say you're building a utility module. You want others to be able to import its functions, but you also want to be able to test it directly.

calculator.py (Our module)

# This function is part of our module's public API.
# Anyone can import and use it.
def add(a, b):
    """This function adds two numbers."""
    print(f"--- Running add({a}, {b}) ---")
    return a + b
# This function is for testing the module.
# We don't want this to run every time someone imports our module.
def test_add_function():
    """A simple test for our add function."""
    print("\n--- Running tests ---")
    result = add(5, 3)
    assert result == 8, f"Test failed: Expected 8, but got {result}"
    print("Test passed!")
# --- The Guardian Block ---
if __name__ == "__main__":
    # This code only runs when you execute "python calculator.py"
    print("Calculator module is being run directly.")
    print("Let's perform a quick test.")
    # Call the test function
    test_add_function()
    # You can also run other code here
    total = add(10, 20)
    print(f"The total is: {total}")

Scenario 1: Running the Module Directly

You run calculator.py from your terminal to test it.

python calculator.py

Output:

Calculator module is being run directly.
Let's perform a quick test.
--- Running tests ---
--- Running add(5, 3) ---
Test passed!
--- Running add(10, 20) ---
The total is: 30

As you can see, everything inside the if __name__ == "__main__": block runs.

Scenario 2: Importing the Module

Now, create another script, main_app.py, that wants to use the add function.

main_app.py

# Import the calculator module
import calculator
print("Welcome to the main application!")
# Use the function from the imported module
sum1 = calculator.add(100, 200)
print(f"Result from main_app: {sum1}")
# The test code from calculator.py should NOT run here.

When you run main_app.py:

python main_app.py

Output:

Welcome to the main application!
--- Running add(100, 200) ---
Result from main_app: 300

Notice that the lines "Calculator module is being run directly" and "Let's perform a quick test" are completely missing. This is because when calculator.py was imported, its __name__ was not "__main__", so the guardian block was skipped.

Summary

Code When it Runs Why it's Useful
def my_function(): ... Always. When the file is imported or run directly. Defines reusable components (functions, classes) that can be used by other scripts.
if __name__ == "__main__": ... Only when the script is executed directly (e.g., python my_script.py). It is skipped on import. Allows you to include code for testing, demonstrations, or script-specific execution without affecting other scripts that import your module.
分享:
扫描分享到社交APP
上一篇
下一篇