Guidelines

λ°μ½”λ ˆμ΄ν„°λ‘œ κ²Œν„°μ™€ μ„Έν„° κ΅¬ν˜„ν•˜κΈ°

λ°μ½”λ ˆμ΄ν„°λ₯Ό μ‚¬μš©ν•œ κ²Œν„°(getter)와 μ„Έν„°(setter) λ©”μ†Œλ“œλŠ” 클래슀의 속성을 μ•ˆμ „ν•˜κ³  효율적으둜 κ΄€λ¦¬ν•˜λŠ” 데 μ‚¬μš©λ©λ‹ˆλ‹€.

κ²Œν„°μ™€ μ„Έν„° μ •μ˜μ— μ‚¬μš©λ˜λŠ” λ°μ½”λ ˆμ΄ν„°λŠ” λ‹€μŒκ³Ό κ°™μŠ΅λ‹ˆλ‹€.

  • @property: κ²Œν„° λ©”μ†Œλ“œλ₯Ό μ •μ˜ν•©λ‹ˆλ‹€. 이 λ©”μ†Œλ“œλŠ” 클래슀 속성을 λ°˜ν™˜ν•©λ‹ˆλ‹€.

  • @속성λͺ….setter: μ„Έν„° λ©”μ†Œλ“œλ₯Ό μ •μ˜ν•©λ‹ˆλ‹€. 이 λ©”μ†Œλ“œλŠ” 클래슀 속성을 μ„€μ • λ˜λŠ” λ³€κ²½ν•©λ‹ˆλ‹€.

λ°μ½”λ ˆμ΄ν„°λ₯Ό μ‚¬μš©ν•œ κ²Œν„°μ™€ μ„Έν„° μ˜ˆμ‹œ
class Person: def __init__(self, name): self._name = name @property # κ²Œν„° λ©”μ†Œλ“œ μ •μ˜ def name(self): return self._name @name.setter # μ„Έν„° λ©”μ†Œλ“œ μ •μ˜ def name(self, value): if isinstance(value, str): self._name = value else: raise ValueError("이름은 λ¬Έμžμ—΄μ΄μ–΄μ•Ό ν•©λ‹ˆλ‹€.") # 클래슀 μ‚¬μš© μ˜ˆμ‹œ person = Person("홍길동") print(person.name) # '홍길동' 좜λ ₯ person.name = "λ°•μ² μˆ˜" print(person.name) # 'λ°•μ² μˆ˜' 좜λ ₯ # 잘λͺ»λœ κ°’ μ„€μ • μ‹œλ„ (였λ₯˜ λ°œμƒ) # person.name = 123

이 μ˜ˆμ œμ—μ„œ Person ν΄λž˜μŠ€λŠ” _name 속성을 가지고 있으며, @property λ°μ½”λ ˆμ΄ν„°λ₯Ό μ‚¬μš©ν•œ name κ²Œν„°μ™€ @name.setter λ°μ½”λ ˆμ΄ν„°λ₯Ό μ‚¬μš©ν•œ name μ„Έν„°λ₯Ό 톡해 이 속성에 μ ‘κ·Όν•©λ‹ˆλ‹€.

Guidelines

AI Tutor

Publish

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result