λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
"곡뢀" π‘Ÿπ‘’π‘π‘œπ‘Ÿπ‘‘/π‘ƒπ‘¦π‘‘β„Žπ‘œπ‘›

[Python] __init__μ΄λž€? / νŒ¨ν‚€μ§€ import 였λ₯˜

by ΰ·† Yoni ΰ·† 2021. 9. 9.
728x90

Pythonμ—μ„œ νŒ¨ν‚€μ§€ νŒŒμΌμ„ κ·Έλƒ₯ importν•œ λ’€
νŒ¨ν‚€μ§€ μ•ˆμ— μžˆλŠ” λͺ¨λ“ˆλ“€μ„ κ·Έλƒ₯ μ‚¬μš©ν•˜λ €κ³  ν•˜λ©΄
였λ₯˜(AttributeError)κ°€ λ°œμƒν•œλ‹€.

예λ₯Ό λ“€μ–΄λ³΄μž.

import shapes

print(shapes.area.circle(5))
print(shapes.volume.sphere(3))

κ°„λ‹¨ν•œ shapesλΌλŠ” νŒ¨ν‚€μ§€λ₯Ό λ§Œλ“€μ–΄μ„œ
νŒ¨ν‚€μ§€ μ•ˆμ— μžˆλŠ” area와 volume λͺ¨λ“ˆμ„ μ‚¬μš©ν•˜λ €κ³  ν•˜λ‹ˆ

AttributeError: module 'shapes' has no attribute 'area'
λΌλŠ” 였λ₯˜κ°€ λ–΄λ‹€.

ν•˜μ§€λ§Œ

from shapes.area

import circle from shapes.volume
import sphere print(circle(5))

print(sphere(3))

λ₯Ό ν•˜λ©΄ 였λ₯˜κ°€ λ°œμƒν•˜μ§€ μ•ŠλŠ”λ‹€.

이 μ΄μœ λŠ” λ¬΄μ—‡μΌκΉŒ?

정닡은 νŒ¨ν‚€μ§€ μ†μ˜ __init__.py 파일 μœ λ¬΄μ— 달렸닀.
*** init은 λ‹€λ“€ μ˜ˆμƒν–ˆκ² μ§€λ§Œ  initialize (μ΄ˆκΈ°ν™”)μ—μ„œ λ”°μ˜¨ 말이닀.

νŒ¨ν‚€μ§€λ§Œ importν•˜κ²Œ 되면 μ•ˆμ— μžˆλŠ” λͺ¨λ“ˆλ“€μ€
ν•¨κ»˜ import λ˜μ§€ μ•ŠλŠ”λ‹€. 이λ₯Ό ν•¨κ»˜ κ°€μ Έμ˜€κΈ° μœ„ν•΄μ„ 
__init__.py 이 ν•„μš”ν•˜λ‹€.

__init__.py

from shapes import area, volume

__init__ νŒŒμΌμ— importλ˜λŠ” λͺ¨λ“ˆλ“€μ€
νŒ¨ν‚€μ§€ μ•ˆμ—λ„ import λœλ‹€κ³  μƒκ°ν•˜λ©΄ λœλ‹€.

이 __init__ 파일과 ν•¨κ»˜ 첫번째 μ½”λ“œλ₯Ό λ‹€μ‹œ 돌렀보면
였λ₯˜(AttributeError)κ°€ λ°œμƒν•˜μ§€ μ•Šκ³  μ½”λ“œκ°€ μ •μƒμ μœΌλ‘œ μ‹€ν–‰λœλ‹€.

κ·Έλ ‡λ‹€λ©΄ κ³Όμ—° 이 __init__.py λŠ” λ¬΄μ—‡μΌκΉŒ?
μ΄λŠ” λ°”λ‘œ __init__ νŒŒμΌμ„ λ‹΄κ³  μžˆλŠ” ν΄λ”λŠ”
Python νŒ¨ν‚€μ§€ μž„μ„ μ•Œλ €μ£ΌλŠ” 역할을 ν•œλ‹€.

파이썬 3.3 ver. μ΄μ „μ—λŠ” __init__ 파일이 ν•„μˆ˜μ˜€λ‹€κ³  ν•œλ‹€.
3.3 ver. μ΄ν›„λΆ€ν„°λŠ” ν•„μˆ˜λŠ” μ•„λ‹ˆμ§€λ§Œ
파이썬 ν•˜μœ„ λ²„μ Όκ³Όμ˜ ν˜Έν™˜μ„±, 그리고 νŒ¨ν‚€μ§€μ˜ λͺ…확성을 μœ„ν•΄
νŒ¨ν‚€μ§€μ— __init__ νŒŒμΌμ„ λ§Œλ“œλŠ” κ±Έ ꢌμž₯ν•œλ‹€κ³  ν•œλ‹€ :-)

728x90

λŒ“κΈ€