Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Câu trả lời ngắn

Đó là mã Boilerplate bảo vệ người dùng khỏi việc vô tình gọi tập lệnh khi họ không có ý định. Dưới đây là một số vấn đề phổ biến khi người bảo vệ bị bỏ qua từ một kịch bản:

Show
  • Nếu bạn nhập tập lệnh không bảo vệ trong một tập lệnh khác (ví dụ:

    # What gets printed if foo is imported as a regular module
    before import
    before function_a
    before function_b
    before __name__ guard
    after __name__ guard
    
    7), thì tập lệnh sau sẽ kích hoạt bản trước để chạy vào thời điểm nhập và sử dụng các đối số dòng lệnh của tập lệnh thứ hai. Đây hầu như luôn luôn là một sai lầm.

  • Nếu bạn có một lớp tùy chỉnh trong tập lệnh không bảo vệ và lưu nó vào tệp Pickle, thì việc giải nén nó trong một tập lệnh khác sẽ kích hoạt nhập tập lệnh không bảo vệ, với các vấn đề tương tự được nêu trong viên đạn trước đó.

Câu trả lời dài

Để hiểu rõ hơn về lý do và làm thế nào điều này quan trọng, chúng ta cần lùi một bước để hiểu làm thế nào Python khởi tạo các tập lệnh và cách điều này tương tác với cơ chế nhập mô -đun của nó.

Bất cứ khi nào trình thông dịch Python đọc một tệp nguồn, nó sẽ làm hai điều:

  • Nó đặt một vài biến đặc biệt như

    # What gets printed if foo is imported as a regular module
    before import
    before function_a
    before function_b
    before __name__ guard
    after __name__ guard
    
    8, và sau đó

  • Nó thực thi tất cả các mã được tìm thấy trong tệp.

Hãy xem cách thức hoạt động của nó và nó liên quan đến câu hỏi của bạn về các kiểm tra

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 mà chúng ta luôn thấy trong các tập lệnh Python.

Mẫu mã

Hãy sử dụng một mẫu mã hơi khác nhau để khám phá cách nhập và tập lệnh hoạt động. Giả sử những điều sau đây là trong một tệp gọi là

# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo2 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    function_a()
    print("m2")
print("t2")
      
0.

# Suppose this is foo.py.

print("before import")
import math

print("before function_a")
def function_a():
    print("Function A")

print("before function_b")
def function_b():
    print("Function B {}".format(math.sqrt(100)))

print("before __name__ guard")
if __name__ == '__main__':
    function_a()
    function_b()
print("after __name__ guard")

Biến đặc biệt

Khi trình thông dịch Python đọc một tệp nguồn, trước tiên nó định nghĩa một vài biến đặc biệt. Trong trường hợp này, chúng tôi quan tâm đến biến

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8.

Khi mô -đun của bạn là chương trình chính

Nếu bạn đang chạy mô -đun của mình (tệp nguồn) làm chương trình chính, ví dụ:

python foo.py

Trình thông dịch sẽ gán chuỗi được mã hóa cứng

# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo2 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    function_a()
    print("m2")
print("t2")
      
2 cho biến
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8, tức là.

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 

Khi mô -đun của bạn được nhập bởi người khác

Mặt khác, giả sử một số mô -đun khác là chương trình chính và nó nhập mô -đun của bạn. Điều này có nghĩa là có một tuyên bố như thế này trong chương trình chính hoặc trong một số mô -đun khác, chương trình chính nhập khẩu:

# Suppose this is in some other main program.
import foo

Trình thông dịch sẽ tìm kiếm tệp

# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo2 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    function_a()
    print("m2")
print("t2")
      
0 của bạn (cùng với việc tìm kiếm một vài biến thể khác) và trước khi thực hiện mô -đun đó, nó sẽ gán tên
# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo2 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    function_a()
    print("m2")
print("t2")
      
5 từ câu lệnh nhập cho biến
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8, tức là.

# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"

Thực hiện mã của mô -đun

Sau khi các biến đặc biệt được thiết lập, trình thông dịch thực thi tất cả các mã trong mô -đun, một câu lệnh tại một thời điểm. Bạn có thể muốn mở một cửa sổ khác ở bên cạnh với mẫu mã để bạn có thể theo dõi cùng với lời giải thích này.

Luôn luôn

  1. Nó in chuỗi

    # Suppose this is foo2.py.
    import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
    
    def function_a():
        print("a1")
        from foo2 import function_b
        print("a2")
        function_b()
        print("a3")
    
    def function_b():
        print("b")
    
    print("t1")
    if __name__ == "__main__":
        print("m1")
        function_a()
        print("m2")
    print("t2")
          
    
    7 (không có báo giá).

  2. Nó tải mô -đun

    # Suppose this is foo2.py.
    import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
    
    def function_a():
        print("a1")
        from foo2 import function_b
        print("a2")
        function_b()
        print("a3")
    
    def function_b():
        print("b")
    
    print("t1")
    if __name__ == "__main__":
        print("m1")
        function_a()
        print("m2")
    print("t2")
          
    
    8 và gán nó cho một biến gọi là
    # Suppose this is foo2.py.
    import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
    
    def function_a():
        print("a1")
        from foo2 import function_b
        print("a2")
        function_b()
        print("a3")
    
    def function_b():
        print("b")
    
    print("t1")
    if __name__ == "__main__":
        print("m1")
        function_a()
        print("m2")
    print("t2")
          
    
    8. Điều này tương đương với việc thay thế
    # Suppose this is foo3.py.
    import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
    
    def function_a():
        print("a1")
        from foo3 import function_b
        print("a2")
        function_b()
        print("a3")
    
    def function_b():
        print("b")
    
    print("t1")
    print("m1")
    function_a()
    print("m2")
    print("t2")
    
    0 bằng cách sau (lưu ý rằng
    # Suppose this is foo3.py.
    import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
    
    def function_a():
        print("a1")
        from foo3 import function_b
        print("a2")
        function_b()
        print("a3")
    
    def function_b():
        print("b")
    
    print("t1")
    print("m1")
    function_a()
    print("m2")
    print("t2")
    
    1 là hàm cấp thấp trong Python lấy chuỗi và kích hoạt nhập thực tế):

# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")
  1. Nó in chuỗi

    # Suppose this is foo3.py.
    import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
    
    def function_a():
        print("a1")
        from foo3 import function_b
        print("a2")
        function_b()
        print("a3")
    
    def function_b():
        print("b")
    
    print("t1")
    print("m1")
    function_a()
    print("m2")
    print("t2")
    
    2.

  2. Nó thực thi khối

    # Suppose this is foo3.py.
    import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
    
    def function_a():
        print("a1")
        from foo3 import function_b
        print("a2")
        function_b()
        print("a3")
    
    def function_b():
        print("b")
    
    print("t1")
    print("m1")
    function_a()
    print("m2")
    print("t2")
    
    3, tạo một đối tượng hàm, sau đó gán đối tượng hàm đó cho một biến gọi là
    # Suppose this is foo3.py.
    import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
    
    def function_a():
        print("a1")
        from foo3 import function_b
        print("a2")
        function_b()
        print("a3")
    
    def function_b():
        print("b")
    
    print("t1")
    print("m1")
    function_a()
    print("m2")
    print("t2")
    
    4.

  3. Nó in chuỗi

    # Suppose this is foo3.py.
    import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
    
    def function_a():
        print("a1")
        from foo3 import function_b
        print("a2")
        function_b()
        print("a3")
    
    def function_b():
        print("b")
    
    print("t1")
    print("m1")
    function_a()
    print("m2")
    print("t2")
    
    5.

  4. Nó thực thi khối

    # Suppose this is foo3.py.
    import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
    
    def function_a():
        print("a1")
        from foo3 import function_b
        print("a2")
        function_b()
        print("a3")
    
    def function_b():
        print("b")
    
    print("t1")
    print("m1")
    function_a()
    print("m2")
    print("t2")
    
    3 thứ hai, tạo một đối tượng hàm khác, sau đó gán nó cho một biến gọi là
    # Suppose this is foo3.py.
    import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
    
    def function_a():
        print("a1")
        from foo3 import function_b
        print("a2")
        function_b()
        print("a3")
    
    def function_b():
        print("b")
    
    print("t1")
    print("m1")
    function_a()
    print("m2")
    print("t2")
    
    7.

  5. Nó in chuỗi

    # Suppose this is foo3.py.
    import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
    
    def function_a():
        print("a1")
        from foo3 import function_b
        print("a2")
        function_b()
        print("a3")
    
    def function_b():
        print("b")
    
    print("t1")
    print("m1")
    function_a()
    print("m2")
    print("t2")
    
    8.

Chỉ khi mô -đun của bạn là chương trình chính

  1. Nếu mô -đun của bạn là chương trình chính, thì nó sẽ thấy rằng
    # What gets printed if foo is imported as a regular module
    before import
    before function_a
    before function_b
    before __name__ guard
    after __name__ guard
    
    8 thực sự đã được đặt thành
    # Suppose this is foo2.py.
    import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
    
    def function_a():
        print("a1")
        from foo2 import function_b
        print("a2")
        function_b()
        print("a3")
    
    def function_b():
        print("b")
    
    print("t1")
    if __name__ == "__main__":
        print("m1")
        function_a()
        print("m2")
    print("t2")
          
    
    2 và nó gọi hai chức năng, in các chuỗi
    python foo.py
    
    01 và
    python foo.py
    
    02.

Chỉ khi mô -đun của bạn được nhập bởi người khác

  1. .instead) If your module is not the main program but was imported by another one, then
    # What gets printed if foo is imported as a regular module
    before import
    before function_a
    before function_b
    before __name__ guard
    after __name__ guard
    
    8 will be
    # Suppose this is foo2.py.
    import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
    
    def function_a():
        print("a1")
        from foo2 import function_b
        print("a2")
        function_b()
        print("a3")
    
    def function_b():
        print("b")
    
    print("t1")
    if __name__ == "__main__":
        print("m1")
        function_a()
        print("m2")
    print("t2")
          
    
    5, not
    # Suppose this is foo2.py.
    import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
    
    def function_a():
        print("a1")
        from foo2 import function_b
        print("a2")
        function_b()
        print("a3")
    
    def function_b():
        print("b")
    
    print("t1")
    if __name__ == "__main__":
        print("m1")
        function_a()
        print("m2")
    print("t2")
          
    
    2, and it'll skip the body of the
    python foo.py
    
    06 statement.

Luôn luôn

  1. Nó in chuỗi
    # Suppose this is foo2.py.
    import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
    
    def function_a():
        print("a1")
        from foo2 import function_b
        print("a2")
        function_b()
        print("a3")
    
    def function_b():
        print("b")
    
    print("t1")
    if __name__ == "__main__":
        print("m1")
        function_a()
        print("m2")
    print("t2")
          
    
    7 (không có báo giá).

Nó tải mô -đun

# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo2 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    function_a()
    print("m2")
print("t2")
      
8 và gán nó cho một biến gọi là
# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo2 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    function_a()
    print("m2")
print("t2")
      
8. Điều này tương đương với việc thay thế
# Suppose this is foo3.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo3 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
print("m1")
function_a()
print("m2")
print("t2")
0 bằng cách sau (lưu ý rằng
# Suppose this is foo3.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo3 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
print("m1")
function_a()
print("m2")
print("t2")
1 là hàm cấp thấp trong Python lấy chuỗi và kích hoạt nhập thực tế):

Nó in chuỗi

# Suppose this is foo3.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo3 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
print("m1")
function_a()
print("m2")
print("t2")
2.

# What gets printed if foo is the main program
before import
before function_a
before function_b
before __name__ guard
Function A
Function B 10.0
after __name__ guard
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard

Nó thực thi khối # Suppose this is foo3.py. import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters def function_a(): print("a1") from foo3 import function_b print("a2") function_b() print("a3") def function_b(): print("b") print("t1") print("m1") function_a() print("m2") print("t2") 3, tạo một đối tượng hàm, sau đó gán đối tượng hàm đó cho một biến gọi là # Suppose this is foo3.py. import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters def function_a(): print("a1") from foo3 import function_b print("a2") function_b() print("a3") def function_b(): print("b") print("t1") print("m1") function_a() print("m2") print("t2") 4.

Nó in chuỗi

# Suppose this is foo3.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo3 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
print("m1")
function_a()
print("m2")
print("t2")
5.

  • Nó thực thi khối

    # Suppose this is foo3.py.
    import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
    
    def function_a():
        print("a1")
        from foo3 import function_b
        print("a2")
        function_b()
        print("a3")
    
    def function_b():
        print("b")
    
    print("t1")
    print("m1")
    function_a()
    print("m2")
    print("t2")
    
    3 thứ hai, tạo một đối tượng hàm khác, sau đó gán nó cho một biến gọi là
    # Suppose this is foo3.py.
    import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
    
    def function_a():
        print("a1")
        from foo3 import function_b
        print("a2")
        function_b()
        print("a3")
    
    def function_b():
        print("b")
    
    print("t1")
    print("m1")
    function_a()
    print("m2")
    print("t2")
    
    7.

  • Nó in chuỗi

    # Suppose this is foo3.py.
    import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
    
    def function_a():
        print("a1")
        from foo3 import function_b
        print("a2")
        function_b()
        print("a3")
    
    def function_b():
        print("b")
    
    print("t1")
    print("m1")
    function_a()
    print("m2")
    print("t2")
    
    8.

  • Chỉ khi mô -đun của bạn là chương trình chính

Nếu mô -đun của bạn là chương trình chính, thì nó sẽ thấy rằng

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 thực sự đã được đặt thành
# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo2 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    function_a()
    print("m2")
print("t2")
      
2 và nó gọi hai chức năng, in các chuỗi
python foo.py
01 và
python foo.py
02.

Thức ăn cho suy nghĩ

  • Câu hỏi: Tôi có thể có nhiều khối kiểm tra

    # What gets printed if foo is imported as a regular module
    before import
    before function_a
    before function_b
    before __name__ guard
    after __name__ guard
    
    8 không? Trả lời: Thật lạ khi làm như vậy, nhưng ngôn ngữ sẽ không ngăn cản bạn.

  • Giả sử những điều sau đây là trong

    python foo.py
    
    11. Điều gì xảy ra nếu bạn nói
    python foo.py
    
    12 trên dòng lệnh? Tại sao?

# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo2 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    function_a()
    print("m2")
print("t2")
      
  • Bây giờ, hãy tìm ra điều gì sẽ xảy ra nếu bạn xóa kiểm tra
    # What gets printed if foo is imported as a regular module
    before import
    before function_a
    before function_b
    before __name__ guard
    after __name__ guard
    
    8 trong
    python foo.py
    
    14:
# Suppose this is foo3.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo3 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
print("m1")
function_a()
print("m2")
print("t2")
  • Điều này sẽ làm gì khi được sử dụng làm kịch bản? Khi được nhập dưới dạng mô -đun?
python foo.py
0

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Tế bào thần kinh

4.6724 Huy hiệu vàng33 Huy hiệu bạc54 Huy hiệu đồng4 gold badges33 silver badges54 bronze badges

Đã trả lời ngày 7 tháng 1 năm 2009 lúc 4:26Jan 7, 2009 at 4:26

Ông Foozmr FoozMr Fooz

106K5 Huy hiệu vàng69 Huy hiệu bạc100 Huy hiệu đồng5 gold badges69 silver badges100 bronze badges

22

Khi tập lệnh của bạn được chạy bằng cách chuyển nó như một lệnh cho trình thông dịch Python,

python foo.py
1

Tất cả các mã ở cấp độ 0 được thực thi. Các chức năng và các lớp được xác định là, được xác định, nhưng không có mã nào của chúng được chạy. Không giống như các ngôn ngữ khác, không có chức năng

python foo.py
15 được chạy tự động - hàm
python foo.py
15 hoàn toàn là tất cả các mã ở cấp cao nhất.

Trong trường hợp này, mã cấp cao nhất là một khối

python foo.py
06.
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 là một biến tích hợp để đánh giá theo tên của mô-đun hiện tại. Tuy nhiên, nếu một mô -đun đang được chạy trực tiếp (như trong
python foo.py
19 ở trên), thì
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 thay vào đó được đặt thành chuỗi
# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo2 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    function_a()
    print("m2")
print("t2")
      
2. Vì vậy, bạn có thể kiểm tra xem tập lệnh của bạn đang được chạy trực tiếp hoặc được nhập bởi một thứ khác bằng cách kiểm tra

python foo.py
2

Nếu tập lệnh của bạn được nhập vào một mô-đun khác, các định nghĩa chức năng và lớp khác nhau của nó sẽ được nhập và mã cấp cao nhất của nó sẽ được thực thi không được đáp ứng. Ví dụ cơ bản, hãy xem xét hai tập lệnh sau:

python foo.py
3
python foo.py
4

Bây giờ, nếu bạn gọi thông dịch viên là

python foo.py
5

Đầu ra sẽ là

python foo.py
6

Nếu bạn chạy

python foo.py
23 thay thế:

python foo.py
7

Bạn lấy

python foo.py
8

Do đó, khi mô -đun

python foo.py
24 được tải, ____78 của nó bằng
python foo.py
26 thay vì
# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo2 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    function_a()
    print("m2")
print("t2")
      
2.

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

TIỀN THƯỞNG

13K15 Huy hiệu vàng42 Huy hiệu bạc76 Huy hiệu đồng15 gold badges42 silver badges76 bronze badges

Đã trả lời ngày 7 tháng 1 năm 2009 lúc 4:28Jan 7, 2009 at 4:28

Adam Rosenfieldadam RosenfieldAdam Rosenfield

380K96 Huy hiệu vàng508 Huy hiệu bạc585 Huy hiệu Đồng96 gold badges508 silver badges585 bronze badges

2

Tạo hai tệp sau:

python foo.py
9
# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
0

Bây giờ chạy từng tệp riêng lẻ.


Chạy

python foo.py
28:

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
1

Khi

python foo.py
29 được thực thi, nó sẽ nhập mô -đun
python foo.py
30. Điều này khiến tất cả các mã bên trong
python foo.py
30 chạy. Python đặt
python foo.py
32 trong mô -đun
python foo.py
30 thành tên của mô -đun,
python foo.py
30.

Chạy

python foo.py
35:

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
2

Khi chỉ thực thi tệp

python foo.py
36, Python đặt
python foo.py
32 trong tệp này thành
# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo2 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    function_a()
    print("m2")
print("t2")
      
2. Do đó, câu lệnh
python foo.py
06 đánh giá thành
python foo.py
40 lần này.

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Mateen Ulhaq

22.3K16 Huy hiệu vàng86 Huy hiệu bạc127 Huy hiệu đồng16 gold badges86 silver badges127 bronze badges

Đã trả lời ngày 7 tháng 1 năm 2009 lúc 11:35Jan 7, 2009 at 11:35

pi.pi.pi.

20,5K7 Huy hiệu vàng38 Huy hiệu bạc59 Huy hiệu Đồng7 gold badges38 silver badges59 bronze badges

0

python foo.py 41 làm gì?

Để phác thảo những điều cơ bản:

  • Biến toàn cầu,

    # What gets printed if foo is imported as a regular module
    before import
    before function_a
    before function_b
    before __name__ guard
    after __name__ guard
    
    8, trong mô -đun là điểm nhập vào chương trình của bạn, là
    python foo.py
    
    43. Nếu không, đó là tên bạn nhập mô -đun theo.

  • Vì vậy, mã trong khối

    python foo.py
    
    06 sẽ chỉ chạy nếu mô -đun là điểm nhập vào chương trình của bạn.

  • Nó cho phép mã trong mô -đun có thể nhập bằng các mô -đun khác mà không thực hiện khối mã bên dưới khi nhập.


Tại sao chúng ta cần điều này?

Phát triển và kiểm tra mã của bạn

Giả sử bạn đang viết một tập lệnh Python được thiết kế để sử dụng làm mô -đun:

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
3

Bạn có thể kiểm tra mô -đun bằng cách thêm cuộc gọi này của hàm vào phía dưới:

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
4

và chạy nó (trên dấu nhắc lệnh) với một cái gì đó như:

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
5

Vấn đề

Tuy nhiên, nếu bạn muốn nhập mô -đun vào một tập lệnh khác:

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
6

Khi nhập, hàm

python foo.py
45 sẽ được gọi, vì vậy bạn có thể nhận xét cuộc gọi chức năng của mình,
python foo.py
46, ở phía dưới.

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
7

Và sau đó bạn sẽ phải nhớ liệu bạn có nhận xét cuộc gọi chức năng kiểm tra của mình hay không. Và sự phức tạp hơn này có nghĩa là bạn có thể quên, làm cho quá trình phát triển của bạn trở nên rắc rối hơn.

Một cách tốt hơn

Biến

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 chỉ vào không gian tên bất cứ nơi nào thông dịch viên Python xảy ra vào lúc này.

Bên trong một mô -đun nhập khẩu, đó là tên của mô -đun đó.

Nhưng bên trong mô -đun chính (hoặc phiên Python tương tác, tức là trình thông dịch đã đọc, eval, in vòng in hoặc thay thế), bạn đang chạy mọi thứ từ

# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo2 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    function_a()
    print("m2")
print("t2")
      
2 của nó.

Vì vậy, nếu bạn kiểm tra trước khi thực hiện:

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
8

Với những điều trên, mã của bạn sẽ chỉ thực thi khi bạn chạy nó dưới dạng mô -đun chính (hoặc cố ý gọi nó từ một tập lệnh khác).

Một cách tốt hơn nữa

Tuy nhiên, có một cách pythonic để cải thiện điều này.

Điều gì sẽ xảy ra nếu chúng ta muốn chạy quy trình kinh doanh này từ bên ngoài mô -đun?

Nếu chúng ta đặt mã chúng ta muốn tập thể dục khi chúng ta phát triển và kiểm tra trong một chức năng như thế này và sau đó kiểm tra

python foo.py
43 ngay sau đó:

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
9

Bây giờ chúng tôi có một chức năng cuối cùng cho phần cuối của mô -đun sẽ chạy nếu chúng tôi chạy mô -đun làm mô -đun chính.

Nó sẽ cho phép mô -đun và các chức năng và lớp của nó được nhập vào các tập lệnh khác mà không cần chạy hàm

python foo.py
50 và cũng sẽ cho phép mô -đun (và các chức năng và lớp của nó) được gọi khi chạy từ một mô -đun
python foo.py
43 khác, tức là.

# Suppose this is in some other main program.
import foo
0

Thành ngữ này cũng có thể được tìm thấy trong tài liệu Python trong một lời giải thích về mô -đun

python foo.py
52. Văn bản đó tuyên bố:

Mô -đun này biểu thị phạm vi (nếu không ẩn danh) trong đó chương trình chính của trình thông dịch thực thi - các lệnh được đọc từ đầu vào tiêu chuẩn, từ tệp tập lệnh hoặc từ một lời nhắc tương tác. Đó là môi trường trong đó tập lệnh có điều kiện thành ngữ của Stanza gây ra một kịch bản để chạy:

# Suppose this is in some other main program.
import foo
1

Đã trả lời ngày 23 tháng 11 năm 2013 lúc 4:38Nov 23, 2013 at 4:38

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

2

python foo.py
53 là phần chạy khi tập lệnh được chạy từ (giả sử) dòng lệnh sử dụng một lệnh như
python foo.py
54.

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Mark Amery

133K78 Huy hiệu vàng395 Huy hiệu bạc444 Huy hiệu đồng78 gold badges395 silver badges444 bronze badges

Đã trả lời ngày 7 tháng 1 năm 2009 lúc 4:14Jan 7, 2009 at 4:14

Harley Holcomharley HolcombeHarley Holcombe

170K15 Huy hiệu vàng69 Huy hiệu bạc63 Huy hiệu Đồng15 gold badges69 silver badges63 bronze badges

2

python foo.py 41 làm gì?

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 là một biến toàn cầu (trong Python, toàn cầu thực sự có nghĩa là ở cấp độ mô -đun) tồn tại trong tất cả các không gian tên. Nó thường là tên của mô -đun (dưới dạng loại
python foo.py
57).

Tuy nhiên, là trường hợp đặc biệt duy nhất, trong bất kỳ quy trình Python nào bạn chạy, như trong mycode.py:

# Suppose this is in some other main program.
import foo
2

Không gian tên toàn cầu ẩn danh khác được gán giá trị

python foo.py
43 cho
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 của nó.

Do đó, bao gồm các dòng cuối cùng

# Suppose this is in some other main program.
import foo
1
  • Ở cuối tập lệnh mycode.py của bạn,
  • Khi nó là mô-đun chính, điểm nhập cảnh được điều hành bởi một quy trình Python,

sẽ khiến chức năng

python foo.py
50 được xác định duy nhất của tập lệnh.

Một lợi ích khác của việc sử dụng cấu trúc này: Bạn cũng có thể nhập mã của mình dưới dạng mô -đun trong một tập lệnh khác và sau đó chạy chức năng chính nếu và khi chương trình của bạn quyết định:

# Suppose this is in some other main program.
import foo
4

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Mateen Ulhaq

22.3K16 Huy hiệu vàng86 Huy hiệu bạc127 Huy hiệu đồng16 gold badges86 silver badges127 bronze badges

Đã trả lời ngày 14 tháng 10 năm 2014 lúc 20:22Oct 14, 2014 at 20:22

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

0

Có rất nhiều sự khác nhau ở đây về các cơ chế của mã được đề cập, "làm thế nào", nhưng đối với tôi, không có ý nghĩa nào cho đến khi tôi hiểu "tại sao". Điều này nên đặc biệt hữu ích cho các lập trình viên mới.

Lấy tệp "ab.py":

# Suppose this is in some other main program.
import foo
5

Và tệp thứ hai "xy.py":

# Suppose this is in some other main program.
import foo
6

Mã này thực sự đang làm gì?

Khi bạn thực hiện

python foo.py
61, bạn
python foo.py
62. Câu lệnh nhập chạy mô -đun ngay lập tức khi nhập, do đó, các hoạt động của ____ 163 được thực thi trước phần còn lại của ____ 164. Sau khi kết thúc với
python foo.py
63, nó tiếp tục với
python foo.py
64.

Trình thông dịch theo dõi các tập lệnh nào đang chạy với

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8. Khi bạn chạy một tập lệnh - bất kể bạn đặt tên cho nó - trình thông dịch gọi nó là
# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo2 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    function_a()
    print("m2")
print("t2")
      
2, biến nó thành tập lệnh chính hoặc 'home' được trả lại sau khi chạy tập lệnh bên ngoài.

Bất kỳ tập lệnh nào khác được gọi từ tập lệnh

# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo2 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    function_a()
    print("m2")
print("t2")
      
2 này đều được gán tên tệp của nó là ____ ____78 (ví dụ:
python foo.py
71). Do đó, dòng
python foo.py
41 là thử nghiệm của trình thông dịch để xác định xem đó có diễn giải/phân tích tập lệnh 'nhà' ban đầu được thực thi hay không, hoặc nếu nó tạm thời nhìn vào tập lệnh khác (bên ngoài). Điều này mang lại sự linh hoạt của lập trình viên để có tập lệnh hoạt động khác nhau nếu nó được thực thi trực tiếp so với được gọi là bên ngoài.

Chúng ta hãy bước qua mã trên để hiểu những gì đang xảy ra, đầu tiên tập trung vào các dòng chưa được giải quyết và thứ tự chúng xuất hiện trong các tập lệnh. Hãy nhớ rằng chức năng đó - hoặc

# Suppose this is foo3.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo3 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
print("m1")
function_a()
print("m2")
print("t2")
3 - Các khối không tự làm bất cứ điều gì cho đến khi chúng được gọi. Những gì người phiên dịch có thể nói nếu lầm bầm với chính nó:

  • Mở xy.py là tệp 'home'; Gọi nó là
    # Suppose this is foo2.py.
    import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
    
    def function_a():
        print("a1")
        from foo2 import function_b
        print("a2")
        function_b()
        print("a3")
    
    def function_b():
        print("b")
    
    print("t1")
    if __name__ == "__main__":
        print("m1")
        function_a()
        print("m2")
    print("t2")
          
    
    2 trong biến
    # What gets printed if foo is imported as a regular module
    before import
    before function_a
    before function_b
    before __name__ guard
    after __name__ guard
    
    8.
  • Nhập và mở tệp với
    python foo.py
    
    71.
  • Oh, một chức năng. Tôi sẽ nhớ điều đó.
  • OK, chức năng
    python foo.py
    
    77; Tôi chỉ học được điều đó. In 'một hàm trong tệp ab'.
  • Phần cuối của tập tin; Quay lại
    # Suppose this is foo2.py.
    import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
    
    def function_a():
        print("a1")
        from foo2 import function_b
        print("a2")
        function_b()
        print("a3")
    
    def function_b():
        print("b")
    
    print("t1")
    if __name__ == "__main__":
        print("m1")
        function_a()
        print("m2")
    print("t2")
          
    
    2!
  • Oh, một chức năng. Tôi sẽ nhớ điều đó.
  • OK, chức năng
    python foo.py
    
    77; Tôi chỉ học được điều đó. In 'một hàm trong tệp ab'.
  • Phần cuối của tập tin; Quay lại
    # Suppose this is foo2.py.
    import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters
    
    def function_a():
        print("a1")
        from foo2 import function_b
        print("a2")
        function_b()
        print("a3")
    
    def function_b():
        print("b")
    
    print("t1")
    if __name__ == "__main__":
        print("m1")
        function_a()
        print("m2")
    print("t2")
          
    
    2!
  • Một cái khác.

Chức năng

python foo.py
79; OK, in 'Nhiệm vụ ngoại vi: có thể hữu ích trong các dự án khác'.

Tại sao thực hiện điều này?

Hãy nhớ những gì tôi đã nói trước đó về báo cáo nhập khẩu? Khi bạn nhập một mô -đun, nó không chỉ 'nhận ra' nó và chờ thêm các hướng dẫn - nó thực sự chạy tất cả các hoạt động thực thi có trong tập lệnh. Vì vậy, đặt phần thịt của tập lệnh của bạn vào chức năng

python foo.py
15 cách ly nó một cách hiệu quả, đặt nó vào sự cô lập để nó không chạy ngay lập tức khi được nhập bởi một tập lệnh khác.

Một lần nữa, sẽ có những ngoại lệ, nhưng thực tế phổ biến là

python foo.py
15 thường không được gọi là bên ngoài. Vì vậy, bạn có thể tự hỏi một điều nữa: nếu chúng ta không gọi
python foo.py
15, tại sao chúng ta lại gọi kịch bản? Đó là bởi vì nhiều người cấu trúc các tập lệnh của họ với các chức năng độc lập được xây dựng để chạy độc lập với phần còn lại của mã trong tệp. Sau đó, họ sau đó được gọi là một nơi khác trong phần thân của kịch bản. Điều này mang lại cho tôi điều này:

Nhưng mã hoạt động mà không có nó

Vâng đúng vậy. Các chức năng riêng biệt này có thể được gọi từ một tập lệnh nội tuyến không có trong hàm

python foo.py
15. Nếu bạn đã quen (như tôi, trong các giai đoạn học lập trình ban đầu của tôi) để xây dựng các tập lệnh nội tuyến thực hiện chính xác những gì bạn cần, và bạn sẽ cố gắng tìm ra nó một lần nữa nếu bạn cần hoạt động đó một lần nữa .. . Chà, bạn không quen với loại cấu trúc nội bộ này với mã của bạn, bởi vì việc xây dựng phức tạp hơn và nó không trực quan để đọc.can be called from an in-line script that's not contained inside a
python foo.py
15 function. If you're accustomed (as I am, in my early learning stages of programming) to building in-line scripts that do exactly what you need, and you'll try to figure it out again if you ever need that operation again ... well, you're not used to this kind of internal structure to your code, because it's more complicated to build and it's not as intuitive to read.

Nhưng đó là một tập lệnh có lẽ không thể có các chức năng của nó được gọi là bên ngoài, bởi vì nếu nó làm ngay lập tức sẽ bắt đầu tính toán và gán các biến. Và rất có thể nếu bạn đang cố gắng sử dụng lại một hàm, tập lệnh mới của bạn có liên quan đủ chặt chẽ với quy mô cũ mà sẽ có các biến mâu thuẫn.

Trong việc chia ra các chức năng độc lập, bạn có khả năng sử dụng lại công việc trước đây của mình bằng cách gọi chúng vào một tập lệnh khác. Ví dụ: "example.py" có thể nhập "xy.py" và gọi

python foo.py
79, sử dụng hàm 'x' từ "xy.py". .

.

Đã trả lời ngày 29 tháng 9 năm 2016 lúc 4:33Sep 29, 2016 at 4:33

Joechojjoechojjoechoj

1.2999 huy hiệu bạc12 Huy hiệu đồng9 silver badges12 bronze badges

0

Mã theo

python foo.py
92 sẽ chỉ được thực thi nếu mô -đun được gọi dưới dạng tập lệnh.

Ví dụ, hãy xem xét mô -đun sau

python foo.py
93:

# Suppose this is in some other main program.
import foo
7

Khả năng đầu tiên: Nhập

python foo.py
93 trong một mô -đun khác

# Suppose this is in some other main program.
import foo
8

Bây giờ nếu bạn gọi

python foo.py
95:

# Suppose this is in some other main program.
import foo
9

Lưu ý rằng chỉ có câu lệnh

python foo.py
96 cấp cao nhất trong
python foo.py
97 được thực thi.


Khả năng thứ hai: Gọi

python foo.py
93 như một kịch bản

Bây giờ nếu bạn chạy

python foo.py
93 dưới dạng tập lệnh Python, cả hai câu lệnh
python foo.py
96 sẽ được thực thi:

# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"
0

Để giải thích toàn diện hơn, bạn có thể đọc những gì

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
01 làm trong Python.

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Đã trả lời ngày 1 tháng 2 năm 2020 lúc 13:26Feb 1, 2020 at 13:26

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

1

Khi có một số câu lệnh nhất định trong mô-đun của chúng tôi (

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
02), chúng tôi muốn được thực thi khi nó sẽ được chạy dưới dạng chính (không nhập), chúng tôi có thể đặt các câu lệnh đó (trường hợp kiểm tra, báo cáo in) trong khối
python foo.py
06 này.

Theo mặc định (khi mô -đun chạy dưới dạng chính, không được nhập), biến

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 được đặt thành
# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo2 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    function_a()
    print("m2")
print("t2")
      
2 và khi nó sẽ được nhập, biến
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 sẽ nhận được một giá trị khác, rất có thể là tên của mô -đun (
# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
07). Điều này rất hữu ích trong việc chạy các biến thể khác nhau của một mô-đun với nhau và tách các câu lệnh đầu vào và đầu ra cụ thể của chúng và cả nếu có bất kỳ trường hợp thử nghiệm nào.

Nói tóm lại, sử dụng khối '

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
08' này để ngăn mã (nhất định) được chạy khi mô -đun được nhập., use this '
# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
08 ' block to prevent (certain) code from being run when the module is imported.

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Đã trả lời ngày 3 tháng 4 năm 2013 lúc 14:09Apr 3, 2013 at 14:09

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Nabeel Ahmednabeel AhmedNabeel Ahmed

17,5K4 Huy hiệu vàng55 Huy hiệu bạc59 Huy hiệu đồng4 gold badges55 silver badges59 bronze badges

1

Nói một cách đơn giản,

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 là một biến được xác định cho mỗi tập lệnh xác định xem tập lệnh có được chạy là mô -đun chính hay nó đang được chạy dưới dạng mô -đun nhập khẩu.

Vì vậy, nếu chúng ta có hai kịch bản;

# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"
1

# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"
2

Đầu ra từ thực thi script1 là

# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"
3

Và đầu ra từ thực thi Script2 là:

# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"
4

Như bạn có thể thấy,

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 cho chúng tôi biết mã nào là mô -đun 'chính'. Điều này là tuyệt vời, bởi vì bạn chỉ có thể viết mã và không phải lo lắng về các vấn đề cấu trúc như trong C/C ++, trong đó, nếu một tệp không thực hiện chức năng 'chính' thì nó không thể được biên dịch như một thực thi và nếu có, Sau đó, nó không thể được sử dụng như một thư viện.

Giả sử bạn viết một kịch bản Python làm một cái gì đó tuyệt vời và bạn thực hiện một loạt các chức năng hữu ích cho các mục đích khác. Nếu tôi muốn sử dụng chúng, tôi chỉ có thể nhập tập lệnh của bạn và sử dụng chúng mà không cần thực hiện chương trình của bạn (cho rằng mã của bạn chỉ thực thi trong bối cảnh

python foo.py
41). Trong khi đó trong C/C ++, bạn sẽ phải chia phần các phần đó thành một mô -đun riêng sau đó bao gồm tệp. Hình dung tình hình dưới đây;

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Các mũi tên là liên kết nhập. Đối với ba mô -đun, mỗi mô -đun đang cố gắng bao gồm mã mô -đun trước đó, có sáu tệp (chín, đếm các tệp triển khai) và năm liên kết. Điều này gây khó khăn cho việc đưa mã khác vào dự án C trừ khi nó được biên dịch cụ thể là thư viện. Bây giờ hãy hình dung nó cho Python:

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Bạn viết một mô -đun và nếu ai đó muốn sử dụng mã của bạn, họ chỉ cần nhập nó và biến

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 có thể giúp tách phần thực thi của chương trình khỏi phần thư viện.

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Đã trả lời ngày 15 tháng 10 năm 2016 lúc 9:07Oct 15, 2016 at 9:07

redbanditredbanditredbandit

2.07215 huy hiệu bạc11 huy hiệu đồng15 silver badges11 bronze badges

1

Hãy nhìn vào câu trả lời theo cách trừu tượng hơn:

Giả sử chúng ta có mã này trong

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
13:

# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"
5

Khối A và B được chạy khi chúng ta đang chạy

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
13.

Nhưng chỉ cần chặn A (và không B) được chạy khi chúng ta đang chạy một mô -đun khác, ví dụ

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
15, trong đó
# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
13 được nhập và mã được chạy từ đó (như khi một hàm trong
# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
13 được gọi từ
# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
15).

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Kubuntu

2.5251 Huy hiệu vàng21 Huy hiệu bạc24 Huy hiệu đồng1 gold badge21 silver badges24 bronze badges

Đã trả lời ngày 20 tháng 1 năm 2015 lúc 17:48Jan 20, 2015 at 17:48

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

AlisaalisaAlisa

2.7723 huy hiệu vàng30 huy hiệu bạc44 Huy hiệu đồng3 gold badges30 silver badges44 bronze badges

0

Để ngắn gọn, bạn cần biết một số điểm:

  1. # It's as if the interpreter inserts this at the top
    # of your module when run as the main program.
    __name__ = "__main__" 
    
    19 Hành động thực sự chạy tất cả những gì có thể chạy trong
    python foo.py
    
    29, có nghĩa là mỗi dòng trong
    python foo.py
    
    29

  2. Vì điểm 1, bạn có thể không muốn mọi thứ được chạy trong

    python foo.py
    
    29 khi nhập nó

  3. Để giải quyết vấn đề ở điểm 2, Python cho phép bạn sử dụng kiểm tra điều kiện

  4. # What gets printed if foo is imported as a regular module
    before import
    before function_a
    before function_b
    before __name__ guard
    after __name__ guard
    
    8 là một biến ẩn trong tất cả các mô -đun
    python foo.py
    
    08:

  • Khi
    python foo.py
    
    29 được
    # It's as if the interpreter inserts this at the top
    # of your module when run as the main program.
    __name__ = "__main__" 
    
    26ed, giá trị của
    # What gets printed if foo is imported as a regular module
    before import
    before function_a
    before function_b
    before __name__ guard
    after __name__ guard
    
    8 của mô -đun
    python foo.py
    
    29 được đặt thành tên tệp của nó "
    # It's as if the interpreter inserts this at the top
    # of your module when run as the main program.
    __name__ = "__main__" 
    
    29"
  • Khi
    python foo.py
    
    29 được chạy trực tiếp bằng cách sử dụng "
    python foo.py
    
    28", giá trị của
    # What gets printed if foo is imported as a regular module
    before import
    before function_a
    before function_b
    before __name__ guard
    after __name__ guard
    
    8 được đặt thành chuỗi
    python foo.py
    
    52
  1. Dựa trên cơ chế làm thế nào Python đặt biến
    # What gets printed if foo is imported as a regular module
    before import
    before function_a
    before function_b
    before __name__ guard
    after __name__ guard
    
    8 cho mỗi mô -đun, bạn có biết cách đạt được điểm 3 không? Câu trả lời khá dễ dàng, phải không? Sử dụng điều kiện IF:
    # It's as if the interpreter inserts this at the top
    # of your module when run as the main program.
    __name__ = "__main__" 
    
    35
  • Sau đó
    python foo.py
    
    28 sẽ chạy phần
    # It's as if the interpreter inserts this at the top
    # of your module when run as the main program.
    __name__ = "__main__" 
    
    37
  • # It's as if the interpreter inserts this at the top
    # of your module when run as the main program.
    __name__ = "__main__" 
    
    19 sẽ bỏ qua phần
    # It's as if the interpreter inserts this at the top
    # of your module when run as the main program.
    __name__ = "__main__" 
    
    37
  1. Bạn thậm chí có thể đặt nếu
    # It's as if the interpreter inserts this at the top
    # of your module when run as the main program.
    __name__ = "__main__" 
    
    40 tùy thuộc vào nhu cầu chức năng của bạn, nhưng hiếm khi

Điều quan trọng mà Python đặc biệt là điểm 4! Phần còn lại chỉ là logic cơ bản.

Tôi đã đọc rất nhiều trong suốt các câu trả lời trên trang này. Tôi sẽ nói, nếu bạn biết điều đó, chắc chắn bạn sẽ hiểu những câu trả lời đó, nếu không, bạn vẫn còn bối rối.

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Đã trả lời ngày 24 tháng 6 năm 2018 lúc 15:48Jun 24, 2018 at 15:48

kiểm trajack

1.61710 Huy hiệu bạc25 Huy hiệu Đồng10 silver badges25 bronze badges

1

Khi bạn chạy Python tương tác, biến

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 cục bộ được gán giá trị là
python foo.py
52. Tương tự như vậy, khi bạn thực thi mô -đun Python từ dòng lệnh, thay vì nhập nó vào một mô -đun khác, thuộc tính
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 của nó được gán giá trị
python foo.py
52, thay vì tên thực của mô -đun. Theo cách này, các mô -đun có thể xem xét giá trị
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 của riêng chúng để tự xác định cách chúng được sử dụng, cho dù là hỗ trợ cho một chương trình khác hoặc là ứng dụng chính được thực hiện từ dòng lệnh. Do đó, thành ngữ sau đây khá phổ biến trong các mô -đun Python:

# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"
6

Đã trả lời ngày 11 tháng 12 năm 2013 lúc 11:23Dec 11, 2013 at 11:23

ZainzainZain

1.2061 Huy hiệu vàng16 Huy hiệu bạc26 Huy hiệu đồng1 gold badge16 silver badges26 bronze badges

Consider:

# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"
7

Nó kiểm tra xem thuộc tính

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 của tập lệnh Python là
# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo2 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    function_a()
    print("m2")
print("t2")
      
2. Nói cách khác, nếu chính chương trình được thực thi, thuộc tính sẽ là
python foo.py
52, do đó chương trình sẽ được thực thi (trong trường hợp này là hàm
python foo.py
15).

Tuy nhiên, nếu tập lệnh Python của bạn được sử dụng bởi một mô -đun, bất kỳ mã nào bên ngoài câu lệnh

python foo.py
06 sẽ được thực thi, do đó
python foo.py
53 được sử dụng chỉ để kiểm tra xem chương trình có được sử dụng làm mô -đun hay không, và do đó quyết định có nên chạy mã không.

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Tripleee

165K27 Huy hiệu vàng250 Huy hiệu bạc298 Huy hiệu Đồng27 gold badges250 silver badges298 bronze badges

Đã trả lời ngày 22 tháng 8 năm 2017 lúc 18:53Aug 22, 2017 at 18:53

LarrylarryLarry

1.2722 Huy hiệu vàng14 Huy hiệu bạc20 Huy hiệu Đồng2 gold badges14 silver badges20 bronze badges

0

Trước khi giải thích bất cứ điều gì về

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
01, điều quan trọng là phải hiểu
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 là gì và nó làm gì.

# What gets printed if foo is imported as a regular module before import before function_a before function_b before __name__ guard after __name__ guard 8 là gì?

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 là một Dunderalias - có thể được coi là một biến toàn cầu (có thể truy cập từ các mô -đun) và hoạt động theo cách tương tự như
# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
56.

Đây là một chuỗi (toàn cầu như đã đề cập ở trên) như được chỉ ra bởi

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
57 (năng suất
# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
58) và là một tiêu chuẩn sẵn có cho cả phiên bản Python 3 và Python 2.

Ở đâu

Nó không chỉ có thể được sử dụng trong các tập lệnh mà còn có thể được tìm thấy trong cả phiên dịch và mô -đun/gói.

Interpreter:

# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"
8

Script:

test_file.py:

# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"
9

Dẫn đến

python foo.py
52

Mô -đun hoặc gói:

somefile.py:

# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")
0

test_file.py:

# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")
1

Dẫn đến

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
60

Lưu ý rằng khi được sử dụng trong một gói hoặc mô -đun,

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 lấy tên của tệp. Đường dẫn của mô -đun thực tế hoặc đường dẫn gói không được đưa ra, nhưng có Dunderalias riêng
# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
62, cho phép điều này.

Bạn sẽ thấy rằng, trong đó

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8, nơi đó là tệp (hoặc chương trình) chính sẽ luôn trả về
python foo.py
52 và nếu đó là một mô -đun/gói nơi nó có nguồn gốc từ.

Thực tiễn

Trở thành một biến có nghĩa là giá trị của nó có thể được ghi đè ("có thể" không có nghĩa là "nên"), ghi đè lên giá trị của

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 sẽ dẫn đến thiếu khả năng đọc. Vì vậy, đừng làm điều đó, vì bất kỳ lý do. Nếu bạn cần một biến xác định một biến mới.

Luôn luôn cho rằng giá trị của

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 là
python foo.py
52 hoặc tên của tệp. Một lần nữa thay đổi giá trị mặc định này sẽ gây ra sự nhầm lẫn nhiều hơn rằng nó sẽ làm tốt, gây ra vấn đề xa hơn xuống dòng.

Example:

# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")
2

Nó được coi là thực hành tốt nói chung để bao gồm

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
01 trong các kịch bản.

Bây giờ để trả lời # It's as if the interpreter inserts this at the top # of your module when run as the main program. __name__ = "__main__" 01:

Bây giờ chúng ta biết hành vi của

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 mọi thứ trở nên rõ ràng hơn:

python foo.py
06 là một câu lệnh điều khiển dòng chảy chứa khối mã sẽ thực thi nếu giá trị được đưa ra là đúng. Chúng tôi đã thấy rằng
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 có thể lấy
python foo.py
52 hoặc tên tệp mà nó đã được nhập từ.

Điều này có nghĩa là nếu

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 bằng
python foo.py
52 thì tệp phải là tệp chính và thực sự phải chạy (hoặc đó là trình thông dịch), không phải là mô -đun hoặc gói được nhập vào tập lệnh.

Nếu thực sự

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 sẽ lấy giá trị của
python foo.py
52 thì bất cứ điều gì có trong khối mã đó sẽ thực thi.

Điều này cho chúng tôi biết rằng nếu tệp chạy là tệp chính (hoặc bạn đang chạy trực tiếp từ trình thông dịch) thì điều kiện đó phải thực thi. Nếu đó là một gói thì nó không nên và giá trị sẽ không phải là

python foo.py
52.

Mô -đun

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 cũng có thể được sử dụng trong các mô -đun để xác định tên của mô -đun

Biến thể

Cũng có thể làm những điều khác, ít phổ biến nhưng hữu ích với

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8, một số tôi sẽ hiển thị ở đây:

Chỉ thực thi nếu tệp là mô -đun hoặc gói

# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")
3

Chạy một điều kiện nếu tệp là cái chính và cái khác nếu nó không

# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")
4

Bạn cũng có thể sử dụng nó để cung cấp các chức năng/tiện ích trợ giúp có thể chạy được trên các gói và mô -đun mà không cần sử dụng các thư viện phức tạp.

Nó cũng cho phép các mô -đun được chạy từ dòng lệnh dưới dạng các tập lệnh chính, cũng có thể rất hữu ích.

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Tripleee

165K27 Huy hiệu vàng250 Huy hiệu bạc298 Huy hiệu Đồng27 gold badges250 silver badges298 bronze badges

Đã trả lời ngày 3 tháng 4 năm 2018 lúc 19:32Apr 3, 2018 at 19:32

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

XantiumxantiumXantium

10,6K10 Huy hiệu vàng58 Huy hiệu bạc87 Huy hiệu đồng10 gold badges58 silver badges87 bronze badges

0

Tôi nghĩ rằng tốt nhất là phá vỡ câu trả lời theo chiều sâu và bằng những từ đơn giản:

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8: Mỗi mô -đun trong Python có một thuộc tính đặc biệt gọi là
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8. Đó là một biến tích hợp trả về tên của mô-đun.

python foo.py
52: Giống như các ngôn ngữ lập trình khác, Python cũng có một điểm nhập cảnh thực thi, tức là, chính.
python foo.py
43 là tên của phạm vi mà mã cấp cao thực thi. Về cơ bản, bạn có hai cách sử dụng mô -đun Python: chạy trực tiếp dưới dạng tập lệnh hoặc nhập nó. Khi một mô -đun được chạy dưới dạng tập lệnh, ____78 của nó được đặt thành
python foo.py
52.

Do đó, giá trị của thuộc tính

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 được đặt thành
python foo.py
52 khi mô -đun được chạy làm chương trình chính. Mặt khác, giá trị của
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 được đặt thành tên của mô -đun.

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Đã trả lời ngày 30 tháng 11 năm 2016 lúc 6:47Nov 30, 2016 at 6:47

Taufiq Rahmantaufiq RahmanTaufiq Rahman

5.4652 Huy hiệu vàng36 Huy hiệu bạc43 Huy hiệu đồng2 gold badges36 silver badges43 bronze badges

Nó là một đặc biệt cho khi một tệp python được gọi từ dòng lệnh. Điều này thường được sử dụng để gọi hàm "chính ()" hoặc thực thi mã khởi động thích hợp khác, như xử lý đối số dòng lệnh.

Nó có thể được viết theo nhiều cách. Cái khác là:

# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")
5

Tôi không nói rằng bạn nên sử dụng điều này trong mã sản xuất, nhưng nó phục vụ để minh họa rằng không có gì "kỳ diệu" về

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
01.

Nó chỉ là một quy ước để gọi một chức năng chính trong các tệp Python.

Đã trả lời ngày 24 tháng 1 năm 2013 lúc 13:48Jan 24, 2013 at 13:48

Giáo sư Falkenprof. FalkenProf. Falken

23.6K18 Huy hiệu vàng100 Huy hiệu bạc169 Huy hiệu đồng18 gold badges100 silver badges169 bronze badges

6

Có một số biến mà hệ thống (trình thông dịch Python) cung cấp cho các tệp nguồn (mô -đun). Bạn có thể nhận được các giá trị của họ bất cứ lúc nào bạn muốn, vì vậy, hãy để chúng tôi tập trung vào biến __name__/thuộc tính:__name__ variable/attribute:

Khi Python tải một tệp mã nguồn, nó thực thi tất cả các mã được tìm thấy trong đó. (Lưu ý rằng nó không gọi tất cả các phương thức và hàm được xác định trong tệp, nhưng nó xác định chúng.)

Trước khi trình thông dịch thực thi tệp mã nguồn, nó xác định một vài biến đặc biệt cho tệp đó; __name__ là một trong những biến đặc biệt mà Python tự động xác định cho mỗi tệp mã nguồn.__name__ is one of those special variables that Python automatically defines for each source code file.

Nếu Python đang tải tệp mã nguồn này làm chương trình chính (nghĩa là tệp bạn chạy), thì nó sẽ đặt biến __name__ đặc biệt cho tệp này có giá trị "__main__".__name__ variable for this file to have a value "__main__".

Nếu điều này được nhập từ một mô -đun khác, __name__ sẽ được đặt thành tên của mô -đun đó.__name__ will be set to that module's name.

Vì vậy, trong ví dụ của bạn một phần:

# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")
6

có nghĩa là khối mã:

# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")
7

sẽ chỉ được thực thi khi bạn chạy mô -đun trực tiếp; Khối mã sẽ không thực thi nếu một mô -đun khác đang gọi/nhập nó vì giá trị của __name__ sẽ không bằng "chính" trong trường hợp cụ thể đó.__name__ will not equal to "main" in that particular instance.

Hy vọng điều này sẽ giúp.

Đã trả lời ngày 25 tháng 11 năm 2015 lúc 12:26Nov 25, 2015 at 12:26

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

CodewizardCodewizardcodewizard

3763 Huy hiệu bạc8 Huy hiệu Đồng3 silver badges8 bronze badges

1

python foo.py
41 về cơ bản là môi trường tập lệnh cấp cao nhất và nó chỉ định trình thông dịch rằng ('Tôi có ưu tiên cao nhất để được thực thi trước').

python foo.py
43 là tên của phạm vi mà mã cấp cao thực thi. Một mô -đun từ ____ ____78 được đặt bằng
python foo.py
43 khi được đọc từ đầu vào tiêu chuẩn, tập lệnh hoặc từ một lời nhắc tương tác.

# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")
8

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Đã trả lời ngày 24 tháng 4 năm 2016 lúc 8:23Apr 24, 2016 at 8:23

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Gr8 adakronthe gr8 adakronThe Gr8 Adakron

1.1721 Huy hiệu vàng12 Huy hiệu bạc14 Huy hiệu đồng1 gold badge12 silver badges14 bronze badges

Consider:

# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")
9

Đầu ra cho những điều trên là

python foo.py
52.

# What gets printed if foo is the main program
before import
before function_a
before function_b
before __name__ guard
Function A
Function B 10.0
after __name__ guard
0

Câu lệnh trên là đúng và in "Phương thức trực tiếp". Giả sử nếu họ nhập lớp này trong một lớp khác, nó không in "Phương thức trực tiếp" bởi vì, trong khi nhập, nó sẽ đặt

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
96.

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Simhumileco

28.8K16 Huy hiệu vàng127 Huy hiệu bạc106 Huy hiệu đồng16 gold badges127 silver badges106 bronze badges

Đã trả lời ngày 22 tháng 6 năm 2016 lúc 10:47Jun 22, 2016 at 10:47

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Nói một cách đơn giản:

Mã bạn thấy trong

python foo.py
41 sẽ chỉ được gọi khi tệp python của bạn được thực thi là
# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
98

Tuy nhiên, nếu bạn muốn nhập tệp Python của mình

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
99 dưới dạng mô -đun để hoạt động với một tệp Python khác, giả sử
# Suppose this is in some other main program.
import foo
00, mã trong
python foo.py
41 sẽ không chạy hoặc có bất kỳ hiệu ứng nào.

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Tripleee

165K27 Huy hiệu vàng250 Huy hiệu bạc298 Huy hiệu Đồng27 gold badges250 silver badges298 bronze badges

Đã trả lời ngày 22 tháng 10 năm 2020 lúc 18:01Oct 22, 2020 at 18:01

Bạn có thể làm cho tệp có thể sử dụng được như một tập lệnh cũng như một mô -đun có thể nhập.script as well as an importable module.

fibo.py (một mô -đun có tên

# Suppose this is in some other main program.
import foo
02)

# What gets printed if foo is the main program
before import
before function_a
before function_b
before __name__ guard
Function A
Function B 10.0
after __name__ guard
1

Tham khảo: https://docs.python.org/3.5/tutorial/modules.html

Đã trả lời ngày 13 tháng 3 năm 2017 lúc 21:44Mar 13, 2017 at 21:44

kgf3JfUtWkgf3JfUtWkgf3JfUtW

12.4K8 Huy hiệu vàng50 Huy hiệu bạc74 Huy hiệu đồng8 gold badges50 silver badges74 bronze badges

Lý giải cho việc

# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"
7

chủ yếu là để tránh các vấn đề khóa nhập khẩu sẽ phát sinh từ việc nhập mã trực tiếp. Bạn muốn

python foo.py
15 chạy nếu tệp của bạn được gọi trực tiếp (đó là trường hợp
# Suppose this is in some other main program.
import foo
04), nhưng nếu mã của bạn được nhập thì nhà nhập khẩu phải nhập mã của bạn từ mô -đun chính thực sự để tránh nhập các vấn đề về khóa.

Một hiệu ứng phụ là bạn tự động đăng nhập vào một phương pháp hỗ trợ nhiều điểm nhập cảnh. Bạn có thể chạy chương trình của mình bằng

python foo.py
15 làm điểm nhập cảnh, nhưng bạn không cần phải làm thế. Trong khi
# Suppose this is in some other main program.
import foo
06 mong đợi
python foo.py
15, các công cụ khác sử dụng các điểm nhập thay thế. Ví dụ: để chạy tệp của bạn dưới dạng quy trình
# Suppose this is in some other main program.
import foo
08, bạn xác định hàm
# Suppose this is in some other main program.
import foo
09 thay vì
python foo.py
15. Cũng giống như với
# Suppose this is in some other main program.
import foo
06,
# Suppose this is in some other main program.
import foo
08 nhập mã của bạn để bạn không muốn nó làm bất cứ điều gì trong khi nó được nhập (vì sự cố khóa nhập khẩu).

Đã trả lời ngày 22 tháng 9 năm 2017 lúc 18:32Sep 22, 2017 at 18:32

personal_cloudpersonal_cloudpersonal_cloud

3.6503 huy hiệu vàng25 Huy hiệu bạc32 Huy hiệu đồng3 gold badges25 silver badges32 bronze badges

0

Nếu bạn là người mới bắt đầu, có lẽ câu trả lời duy nhất bạn cần ngay bây giờ là mã này không cần thiết cho một tập lệnh đơn giản. Nó chỉ hữu ích nếu bạn muốn có thể

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
26 tập lệnh của bạn (hoặc
# Suppose this is in some other main program.
import foo
14, v.v. xem các câu trả lời khác ở đây cho một số kịch bản không phải là Beginner khác).

Trong các từ hơi khác nhau, người bảo vệ

# Suppose this is in some other main program.
import foo
15 là một cơ chế để ẩn mã khỏi mã khác. Nếu bạn không có lý do cụ thể để ẩn một cái gì đó, đừng: Nếu bạn không cần phải ẩn một số mã từ
# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
26, đừng đặt nó đằng sau người bảo vệ này và nếu bạn làm, ẩn ít nhất có thể.

Nói chi tiết hơn một chút, giả sử bạn có một tập lệnh đơn giản

# Suppose this is in some other main program.
import foo
17 (được điều chỉnh từ câu trả lời này):

# What gets printed if foo is the main program
before import
before function_a
before function_b
before __name__ guard
Function A
Function B 10.0
after __name__ guard
3

Bây giờ, nếu bạn chỉ cần chạy

# Suppose this is in some other main program.
import foo
18 thì nó hoạt động tốt. Nhưng
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 sẽ luôn là
# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo2 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    function_a()
    print("m2")
print("t2")
      
2 trong kịch bản này, vì vậy điều kiện thực sự không cần thiết. Kịch bản có thể được đơn giản hóa thành chỉ

# What gets printed if foo is the main program
before import
before function_a
before function_b
before __name__ guard
Function A
Function B 10.0
after __name__ guard
4

Bây giờ, bạn không thể

# Suppose this is in some other main program.
import foo
21 với phiên bản mới, nhưng nếu bạn không có kế hoạch làm điều đó ngay từ đầu, phiên bản này thực sự tốt hơn, bởi vì nó đơn giản và rõ ràng hơn.

Nếu bạn muốn có thể

# Suppose this is in some other main program.
import foo
21, phiên bản đầu tiên cũng vô dụng, vì mã hữu ích nằm trong một phần sẽ không chạy khi bạn
# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
26 tệp này (trong trường hợp đó
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 sẽ không
# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo2 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    function_a()
    print("m2")
print("t2")
      
2). Thiết kế phù hợp trong trường hợp đó sẽ là tái cấu trúc mã để các phần hữu ích nằm trong một chức năng bạn có thể chạy khi bạn muốn sau khi bạn đã
# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
26ed nó.

# What gets printed if foo is the main program
before import
before function_a
before function_b
before __name__ guard
Function A
Function B 10.0
after __name__ guard
5

Bây giờ, nếu bạn

# Suppose this is in some other main program.
import foo
21, cuộc gọi đến
python foo.py
15 sẽ không được thực thi; Nhưng khi bạn chạy
# Suppose this is in some other main program.
import foo
18, nó sẽ.

Trên thực tế, một thiết kế tốt hơn vẫn sẽ là cô lập phần có thể tái sử dụng (tính toán thực tế) khỏi đầu vào/đầu ra có thể nhìn thấy của người dùng:

# What gets printed if foo is the main program
before import
before function_a
before function_b
before __name__ guard
Function A
Function B 10.0
after __name__ guard
6

Bây giờ, bạn có thể

# Suppose this is in some other main program.
import foo
30 và gọi hàm
# Suppose this is in some other main program.
import foo
31 từ mã thực hiện
# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
26 này.

.

Tương tự, bạn có thể

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 
26 và gọi hàm
python foo.py
50 nếu bạn muốn sử dụng lại nó.

Quay trở lại mã trong câu hỏi, tôi cũng sẽ chuyển mã từ

python foo.py
06 thành một chức năng, để người gọi có thể gọi chức năng đó nếu họ muốn.

# What gets printed if foo is the main program
before import
before function_a
before function_b
before __name__ guard
Function A
Function B 10.0
after __name__ guard
7

Điều này thay đổi phạm vi của biến

# Suppose this is in some other main program.
import foo
39; Nếu mã xung quanh cần truy cập vào nó, bạn sẽ cần phải làm cho nó ____256 (hoặc, có lẽ, tốt hơn, tái cấu trúc
python foo.py
50 thành
# Suppose this is in some other main program.
import foo
42 và người gọi nắm bắt giá trị trong một biến cục bộ của riêng nó).

(Không giống như trong các ngôn ngữ như C, tên

python foo.py
50 không có ý nghĩa cụ thể đối với Python; nhưng đó là một quy ước phổ biến để sử dụng nó như tên của thứ sẽ được chạy. Bạn vẫn phải thực sự gọi nó một cách rõ ràng, như
python foo.py
15, không giống như trong C.)

Đã trả lời ngày 30 tháng 10 năm 2021 lúc 9:46Oct 30, 2021 at 9:46

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Tripleetripleeetripleee

165K27 Huy hiệu vàng250 Huy hiệu bạc298 Huy hiệu Đồng27 gold badges250 silver badges298 bronze badges

3

Mỗi mô -đun trong Python có một thuộc tính gọi là

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8. Giá trị của thuộc tính
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 là
python foo.py
52 khi mô -đun được chạy trực tiếp, như
# Suppose this is in some other main program.
import foo
48. Mặt khác (như khi bạn nói
# Suppose this is in some other main program.
import foo
49) Giá trị của
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 là tên của mô -đun.

Ví dụ nhỏ để giải thích ngắn gọn.

Script test.py

# What gets printed if foo is the main program
before import
before function_a
before function_b
before __name__ guard
Function A
Function B 10.0
after __name__ guard
8

Chúng ta có thể thực hiện trực tiếp điều này như

# What gets printed if foo is the main program
before import
before function_a
before function_b
before __name__ guard
Function A
Function B 10.0
after __name__ guard
9

Đầu ra

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
0

Bây giờ giả sử chúng ta gọi tập lệnh trên từ một tập lệnh khác:

Tập lệnh bên ngoài_calling.py

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
1

Khi bạn thực hiện điều này,

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
2

Đầu ra

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
3

Bây giờ giả sử chúng ta gọi tập lệnh trên từ một tập lệnh khác:

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Tập lệnh bên ngoài_calling.pyJun 12, 2019 at 9:28

Khi bạn thực hiện điều này,Rishi Bansal

Vì vậy, ở trên là tự giải thích rằng khi bạn gọi thử nghiệm từ một tập lệnh khác, nếu vòng lặp

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 trong
# Suppose this is in some other main program.
import foo
52 sẽ không thực thi.2 gold badges24 silver badges44 bronze badges

Đã trả lời ngày 12 tháng 6 năm 2019 lúc 9:28

  1. Rishi Bansalrishi Bansal

  2. 3,4772 Huy hiệu vàng24 Huy hiệu bạc44 Huy hiệu đồng

Câu trả lời này dành cho các lập trình viên Java học Python. Mỗi tệp Java thường chứa một lớp công khai. Bạn có thể sử dụng lớp đó theo hai cách:

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Gọi lớp từ các tệp khác. Bạn chỉ cần nhập nó trong chương trình gọi.

Chạy lớp đứng một mình, cho mục đích thử nghiệm.18 gold badges135 silver badges203 bronze badges

Đối với trường hợp sau, lớp nên chứa một phương thức chính () tĩnh công khai. Trong Python, mục đích này được phục vụ bởi nhãn được xác định trên toàn cầu

python foo.py
43.Oct 7, 2018 at 4:52

EYLLLANESCRaja

227K18 Huy hiệu vàng135 Huy hiệu bạc203 Huy hiệu đồng11 silver badges13 bronze badges

0

Đã trả lời ngày 7 tháng 10 năm 2018 lúc 4:52

Rajaraja

96611 Huy hiệu bạc13 Huy hiệu đồng

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Nếu tệp .py này được nhập bởi các tệp .py khác, mã trong câu lệnh

python foo.py
06 sẽ không được thực thi.

165K27 Huy hiệu vàng250 Huy hiệu bạc298 Huy hiệu Đồng27 gold badges250 silver badges298 bronze badges

Mỗi mô -đun trong Python có một thuộc tính gọi là

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8. Giá trị của thuộc tính
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 là
python foo.py
52 khi mô -đun được chạy trực tiếp, như
# Suppose this is in some other main program.
import foo
48. Mặt khác (như khi bạn nói
# Suppose this is in some other main program.
import foo
49) Giá trị của
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 là tên của mô -đun.Jun 19, 2018 at 11:44

pah8Jpah8Jpah8J

Ví dụ nhỏ để giải thích ngắn gọn.7 silver badges15 bronze badges

Script test.py

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
4

Chúng ta có thể thực hiện trực tiếp điều này nhưyou can see me.

Đầu ra

Bây giờ giả sử chúng ta gọi tập lệnh trên từ một tập lệnh khác:You can't see me.

Tập lệnh bên ngoài_calling.py

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Khi bạn thực hiện điều này,Jul 30, 2019 at 16:22

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Vì vậy, ở trên là tự giải thích rằng khi bạn gọi thử nghiệm từ một tập lệnh khác, nếu vòng lặp

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 trong
# Suppose this is in some other main program.
import foo
52 sẽ không thực thi.

Đã trả lời ngày 12 tháng 6 năm 2019 lúc 9:28

Rishi Bansalrishi Bansal

3,4772 Huy hiệu vàng24 Huy hiệu bạc44 Huy hiệu đồng

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
5

Câu trả lời này dành cho các lập trình viên Java học Python. Mỗi tệp Java thường chứa một lớp công khai. Bạn có thể sử dụng lớp đó theo hai cách:

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
6

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Nếu tệp .py này được nhập bởi các tệp .py khác, mã trong câu lệnh

python foo.py
06 sẽ không được thực thi.

165K27 Huy hiệu vàng250 Huy hiệu bạc298 Huy hiệu Đồng27 gold badges250 silver badges298 bronze badges

Mỗi mô -đun trong Python có một thuộc tính gọi là

# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8. Giá trị của thuộc tính
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 là
python foo.py
52 khi mô -đun được chạy trực tiếp, như
# Suppose this is in some other main program.
import foo
48. Mặt khác (như khi bạn nói
# Suppose this is in some other main program.
import foo
49) Giá trị của
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard
8 là tên của mô -đun.Apr 4, 2018 at 14:32

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Ví dụ nhỏ để giải thích ngắn gọn.Ali Hallaji

Script test.py2 gold badges27 silver badges35 bronze badges

Chúng ta có thể thực hiện trực tiếp điều này như

Đầu ra

Bây giờ giả sử chúng ta gọi tập lệnh trên từ một tập lệnh khác:

Vì vậy, đó là những gì dòng mã này kiểm tra. Nếu đó là tệp chính (nghĩa là, B.Py) chạy mã, trong trường hợp này không (a.py là tệp chính đang chạy), thì chỉ có mã được thực thi.

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

Đã trả lời ngày 4 tháng 5 năm 2018 lúc 8:25May 4, 2018 at 8:25

Hướng dẫn what is if __ main __ in python? - nếu __ main __ trong python là gì?

__ Main __ có nghĩa là gì trong Python?

Trong Python, tên đặc biệt __main__ được sử dụng cho hai cấu trúc quan trọng: tên của môi trường cấp cao nhất của chương trình, có thể được kiểm tra bằng cách sử dụng biểu thức __name__ == '__main__'; và. Tệp __main__.py trong các gói Python.the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.

Nếu __ name__ chính là gì?

Về mặt cú pháp, Python's If __name__ == "__main__" Idiom chỉ là một khối có điều kiện bình thường: 1if __name__ == "__main__"Dòng 1 đánh giá là đúng.a normal conditional block: 1if __name__ == "__main__": 2 ... The indented block starting in line 2 contains all the code that Python will execute when the conditional statement in line 1 evaluates to True .

Nếu chính làm gì trong Python?

Nếu __name__ == "__main__" trong hành động, chúng tôi sử dụng if-satement để chạy các khối mã nếu chương trình của chúng tôi là chương trình chính được thực hiện.Điều này cho phép chương trình của chúng tôi có thể tự thực hiện được, nhưng thân thiện với các mô -đun Python khác, những người có thể muốn nhập một số chức năng mà không phải chạy mã.run blocks of code only if our program is the main program executed. This allows our program to be executable by itself, but friendly to other Python modules who may want to import some functionality without having to run the code.

Main () có nghĩa là gì trong Python?

Chức năng chính trong Python đóng vai trò là điểm thực hiện cho bất kỳ chương trình nào.Xác định chức năng chính trong lập trình Python là một điều cần thiết để bắt đầu thực hiện chương trình vì nó chỉ được thực thi khi chương trình được chạy trực tiếp và không được thực thi khi được nhập dưới dạng mô -đun.acts as the point of execution for any program. Defining the main function in Python programming is a necessity to start the execution of the program as it gets executed only when the program is run directly and not executed when imported as a module.