Python๐Ÿค”์—์„œ "__name__"(ํŠน์ˆ˜ ๋ณ€์ˆ˜)์€ ์‹ค์ œ๋กœ ๋ฌด์—‡์ž…๋‹ˆ๊นŒ?

๋‹น์‹ ์€ ํŒŒ์ดํ† ๋‹ˆ์Šคํƒ€์ž…๋‹ˆ๊นŒ? ๊ทธ๋ ‡๋‹ค๋ฉด "_name_"๋ฐ "_main_"์ด ์‹ค์ œ๋กœ ๋ฌด์—‡์ด๋ฉฐ ์–ด๋–ป๊ฒŒ ์ž‘๋™ํ•˜๋Š”์ง€ ๋ช…ํ™•ํ•˜๊ฒŒ ์‚ดํŽด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

file1์— ๋‹ค์Œ ์ฝ”๋“œ๊ฐ€ ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

# File1.py 

print ("File1 __name__ = %s" %__name__) 

if __name__ == "__main__": 
    print ("File1 is being run directly")
else: 
    print ("File1 is being imported")


๋ฌผ๋ก  ์ด๊ฒƒ์€ file2์— ์žˆ์Šต๋‹ˆ๋‹ค.

# File2.py

import file1

print("File2 __name__ = %s" % __name__)

if __name__ == "__main__":
    print("File2 is being run directly")
else:
    print("File2 is being imported")


ํŒŒ์ผ 1์„ ์‹คํ–‰ํ•˜๋ฉด ์ถœ๋ ฅ์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

File1 __name__ = __main__
File1 is being run directly


๊ทธ๋ฆฌ๊ณ  file2๋ฅผ ์‹คํ–‰ํ•˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ถœ๋ ฅ๋ฉ๋‹ˆ๋‹ค.

File1 __name__ = file1
File1 is being imported
File2 __name__ = __main__
File2 is being run directly


์ถœ๋ ฅ์„ ์ฃผ์˜ ๊นŠ๊ฒŒ ๋ณธ ๊ฒฝ์šฐ *_name_ *์€ ํ˜„์žฌ ๋ชจ๋“ˆ์˜ ์ด๋ฆ„์œผ๋กœ ํ‰๊ฐ€๋˜๋Š” ๋‚ด์žฅ ๋ณ€์ˆ˜์ž…๋‹ˆ๋‹ค.

๋•Œ๋•Œ๋กœ _main_๐Ÿค”์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ์ด์œ ๋ฅผ ๋ฌผ์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.



ํ˜„์žฌ ์Šคํฌ๋ฆฝํŠธ๊ฐ€ ์ž์ฒด์ ์œผ๋กœ ์‹คํ–‰ ์ค‘์ธ ๊ฒฝ์šฐ _name_ ๋ณ€์ˆ˜๋Š” *main *์„ ๋ฐ˜ํ™˜ํ•˜๊ณ  ์Šคํฌ๋ฆฝํŠธ๋ฅผ ๊ฐ€์ ธ์˜จ ๊ฒฝ์šฐ _name_์€ ๋ชจ๋“ˆ ์ด๋ฆ„์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

๋น„๊ณ : _name_์€ ํ•ญ์ƒ ๋ฌธ์ž์—ด ๋ฐ์ดํ„ฐ ์œ ํ˜•์ž…๋‹ˆ๋‹ค.

ํŒŒ์ผ 2๋ฅผ ์‹คํ–‰ํ•˜๋Š” ๊ฒฝ์šฐ ์œ„์˜ ์˜ˆ๋ฅผ ์‚ดํŽด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. file1์˜ _name_ ๋ณ€์ˆ˜๋Š” ์šฐ๋ฆฌ๊ฐ€ ๊ฐ€์ ธ์˜ค๋Š” ๋ชจ๋“ˆ์˜ ์ด๋ฆ„์ด๊ธฐ ๋•Œ๋ฌธ์— file1์ด ๋˜๊ณ  file2์˜ _name_์€ ์šฐ๋ฆฌ๊ฐ€ ์‹คํ–‰ ์ค‘์ธ ๋ชจ๋“ˆ์ด๋ฏ€๋กœ __main__์ด ๋ฉ๋‹ˆ๋‹ค.

_name_ ๋ณ€์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ฐ€์ ธ์˜จ ํด๋ž˜์Šค์˜ ์ด๋ฆ„์„ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์˜ˆ์‹œ

from player import Player

print(Player.__name__) 
# OUTPUT: Player


์œ„์—์„œ ๋งํ•œ ๋ชจ๋“  ๊ฒƒ์„ ์š”์•ฝํ•˜๋ฉด _name_ ๋ณ€์ˆ˜(์•ž๊ณผ ๋’ค์— ๋‘ ๊ฐœ์˜ ๋ฐ‘์ค„)๋Š” ํŠน๋ณ„ํ•œ Python ๋ณ€์ˆ˜์ž…๋‹ˆ๋‹ค. ํฌํ•จํ•˜๋Š” ์Šคํฌ๋ฆฝํŠธ๋ฅผ ์‹คํ–‰ํ•˜๋Š” ๋ฐฉ๋ฒ•์— ๋”ฐ๋ผ ๊ฐ’์„ ์–ป์Šต๋‹ˆ๋‹ค.

์ด ํŠน์ˆ˜ ๋ณ€์ˆ˜ ๋•๋ถ„์— ์Šคํฌ๋ฆฝํŠธ๋ฅผ ์‹คํ–‰ํ• ์ง€ ์—ฌ๋ถ€๋ฅผ ๊ฒฐ์ •ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋˜๋Š” ์Šคํฌ๋ฆฝํŠธ์— ์ •์˜๋œ ๊ธฐ๋Šฅ์„ ๊ฐ€์ ธ์˜ค๋ ค๋Š” ๊ฒฝ์šฐ.

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ