อ็อบเจ็กต์โมดูลมีลักษณะเฉพาะโดยแอตทริบิวต์ต่างๆ ชื่อแอตทริบิวต์นำหน้าและท้ายด้วย underscore คู่ __ แอตทริบิวต์สำคัญที่สุดของโมดูลคือ __name__ เมื่อ Python รันในฐานะโค้ดที่รันได้ระดับบนสุด (top-level executable code) เช่น เมื่ออ่านจาก standard input, สคริปต์, หรือจากพรอมต์โต้ตอบ แอตทริบิวต์ __name__ จะถูกตั้งค่าเป็น '__main__'
>>> __name__ '__main__'
จากภายในสคริปต์ด้วย เราพบว่าค่าของแอตทริบิวต์ __name__ ถูกตั้งค่าเป็น '__main__' รันสคริปต์ต่อไปนี้:
'module docstring'
print('name of module:', __name__)
ผลลัพธ์
name of module: __main__
อย่างไรก็ตาม สำหรับโมดูลที่ถูกนำเข้า แอตทริบิวต์นี้จะถูกตั้งค่าเป็นชื่อของสคริปต์ Python สำหรับโมดูล hello.py:
>>> import hello >>> hello.__name__ hello
เห็นได้ว่าค่าของ __name__ ถูกตั้งค่าเป็น __main__ สำหรับโมดูลระดับบนสุด แต่สำหรับโมดูลที่นำเข้า จะถูกตั้งค่าเป็นชื่อไฟล์ รันสคริปต์ต่อไปนี้ (moduletest.py):
import hello
print('name of top level module:', __name__)
print('name of imported module:', hello.__name__)
ผลลัพธ์
name of top level module: __main__ name of imported module: hello
สคริปต์ Python ที่มีฟังก์ชันอาจมีโค้ดที่รันได้บางส่วน ดังนั้น หากเรานำเข้า โค้ดของมันจะถูกรันอัตโนมัติ เรามีสคริปต์ messages.py ที่มี 2 ฟังก์ชัน ในส่วนที่รันได้ รับอินพุตจากผู้ใช้เป็นอาร์กิวเมนต์ของฟังก์ชัน thanks():
def welcome(name):
print("Hi {}. Welcome to TutorialsPoint".format(name))
return
def thanks(name):
print("Thank you {}. See you again".format(name))
name = input('enter name:')
thanks(name)
ชัดเจนว่าเมื่อเรารัน messages.py เอาต์พุทจะแสดงข้อความ thanks ดังนี้:
enter name:Ajit Thank you Ajit. See you again
เรามีสคริปต์ moduletest.py ดังนี้:
import messages
print('name of top level module:', __name__)
print('name of imported module:', messages.__name__)
ตอนนี้ถ้าเรารันสคริปต์ moduletest.py เราจะพบว่าคำสั่ง input และการเรียก welcome() จะถูกรัน:
c:\python37>python moduletest.py
ผลลัพธ์
enter name:Kishan Thank you Kishan. See you again enter name:milind Hi milind. Welcome to TutorialsPoint
นี่คือเอาต์พุทของทั้งสองสคริปต์ แต่เราต้องการนำเข้าฟังก์ชันจากโมดูล messages แต่ไม่ใช่โค้ดที่รันได้ในมัน
นี่คือที่ที่ข้อเท็จจริงที่ว่าค่าของแอตทริบิวต์ __name__ ของสคริปต์ระดับบนสุดคือ __main__ มีประโยชน์ เปลี่ยนสคริปต์ messages.py ให้รันคำสั่ง input และการเรียกฟังก์ชันก็ต่อเมื่อ __name__ เท่ากับ __main__:
"docstring of messages module"
def welcome(name):
print("Hi {}. Welcome to TutorialsPoint".format(name))
return
def thanks(name):
print("Thank you {}. See you again".format(name))
if __name__ == '__main__':
name = input('enter name')
thanks(name)
ใช้เทคนิคข้างต้นเมื่อใดก็ตามที่คุณต้องการโมดูลที่สามารถรันได้และนำเข้าได้ โมดูล moduletest.py ไม่ต้องเปลี่ยนแปลง ส่วนที่รันได้ในโมดูล messages จะไม่รันแล้ว:
enter name: milind Hi milind. Welcome to TutorialsPoint
สังเกตว่านี่ไม่ได้ป้องกันไม่ให้คุณรันสคริปต์ messages.py แบบอิสระ