@property in Python
References: [์ฑ ] ํ์ด์ฌ ์ฝ๋ฉ์ ๊ธฐ์ - ๋ธ๋ ์ฌ๋ผํจ ์ง์
Access Modifier
Python ์๋
private
,public
,protected
,default
๋ฑ์ keyword access modifier๊ฐ ์กด์ฌํ์ง ์๊ณ , ์๋ช ๋ฒ (naming)์ผ๋ก ์ ์ดํ๋คํ์ด์ฌ์์ ์ ์ธ๋๋ ๋ชจ๋ variable๊ณผ method๋
public
์ด๊ธฐ ๋๋ฌธ์getter
๋setter
method๊ฐ ์๋ค!์ฒซ ์ธ์ด๊ฐ Java์ธ ๋์๊ฒ ์๋ก์ ๋ Python ์ ํน์ง!
| public | protected | private | | ------------------ | ----------------------- | ------------------------ | | ์ ๋์ฌ์ ๋ฐ์ค ์์ | ์ ๋์ฌ์ ๋ฐ์ค ํ ๊ฐ (_) | ์ ๋์ฌ์ ๋ฐ์ค ๋ ๊ฐ (__) |
ex)
Getters and Setters in Python
1. Get, Set method ์ง์ ๋ง๋ค์ด ๋ณด๊ธฐ
์ง์ ๊ตฌํ
ex)
๊ฐ๋จํ์ง๋ง Pythonic ํ์ง ์๋ค!
2. @property
, @__.setter
decorator ์ฌ์ฉํ๊ธฐ
@property
, @__.setter
decorator ์ฌ์ฉํ๊ธฐ์ง์ ๊ตฌํํ ๋ ๋ณด๋ค ๋ ์ง๊ด์ ์ผ๋ก ํํ ๊ฐ๋ฅ!
property class๋?
special descriptor object๋ฅผ ์์ฑํ๋ class
๋ด๋ถ์
getter
,setter
,deleter
method๋ฅผ ๊ฐ์ง๊ณ ์์ex)
์คํ ๊ฒฐ๊ณผ
property decorator ์ฌ์ฉํ๊ธฐ
Instance ๊ฐ์ฒด์ variable ์ ๊ทผ์ method๋ก ์ ์ฝํ๊ธฐ ์ํด์๋ property ๊ฐ์ฒด๋ก Instance ๊ฐ์ฒด์ variable์ wrapping ํด์ผํจ
ex)
@property
@property
getter์ ์ญํ
method ์์
@property
decorator๋ฅผ ๋ถ์ด๋ฉด ๋ด๋ถ์ ์ผ๋ก ํด๋น method๋ช ์ instance๊ฐ ๋ง๋ค์ด์ง๊ณ , ๊ทธ ๋ด๋ถ์ ์ด method๊ฐ getter๋ก ๋ฑ๋ก๋จ
@[getter_method_name].setter
@[getter_method_name].setter
setter์ ์ญํ
@property ๊ฐ setter๋ณด๋ค ์์ ์์ด์ผ ํ๋ค
@property
์์ด @ํจ์๋ช .setter ๋ง ์์ผ๋ฉด error๊ฐ ๋ฐ์ํ๋คbut, setter ์์ด
@property
๋ง ์ฌ์ฉํ์ฌ getter๋ง ์ ์ธ ํ๋ ๊ฒ์ ๊ฐ๋ฅํ๋ค์ด๋ ๊ฒ ํ๋ฉด ์ฝ๊ธฐ ์ ์ฉ private data ๊ฐ ๋๋ค
3. @property
decorator ๋ฅผ ์ฌ์ฉํ๋ ์ด์
@property
decorator ๋ฅผ ์ฌ์ฉํ๋ ์ด์ ์ ๋๋ก ๋๋ตํ์ง ๋ชปํ ๊ฒ์ด ๊ณ์ ์๊ฐ๋์ ๋ค์ ์ ๋ฆฌ,,,,ํํ ์๊ฐ์ ๋๋ฆฌ๊ณ ์ถ์
์ฌ์ฉ์๊ฐ ์์ฑ์ ์ง์ ์ ๊ทผ์ ๋ง๊ธฐ ์ํด ์ฌ์ฉ
Encapsulation
์ ์ํด ์ฌ์ฉClass๋ฅผ ์ ์ํ ๋ ๋ด๋ถ์ ์์ฑ๊ณผ method๋ฅผ ๋ฌถ์ด์ ํ๋์ ๋จ์๋ก ์ฒ๋ฆฌํ ์ ์๋๋ฐ, ์ด๋ ๊ฒ ํ๋์ ๋จ์๋ก ๋ฌถ์ด์ class๋ฅผ ๋ง๋๋ ๊ฒ์
Encapsulation
์ด๋ผ๊ณ ํ๋คClass instance ๋ด๋ถ์์ ์ฌ์ฉ๋๋ ๋ณ์๋ฅผ ๋ณดํธํ๊ธฐ ์ํ ๊ฒ
why?
์ธ๋ถ์์ ๋ณ์๋ฅผ ๋ง์๋๋ก ์กฐ์์ด ๊ฐ๋ฅํ๋ฉด, class ๊ฐ ์ ํด๋์ logic๋๋ก ์๋ํ์ง ์๊ณ error๊ฐ ๋ฐ์ํ ๊ฐ๋ฅ์ฑ์ด ๋๊ธฐ ๋๋ฌธ
๊ทธ๋์ OOP์์๋ Encapsulation ์ ํตํด ํจ์ ๋ด๋ถ์์ ์ฌ์ฉ๋๋ ๋ณ์์ ์ธ๋ถ์์ ์ฌ์ฉ๋๋ ๋ณ์๋ฅผ ๊ตฌ๋ถํ๋ค!
๋์ค์ ์์ฑ์ ์ค์ ํ ๋ ํน๋ณํ ๋์์ด ์ผ์ด๋์ผ ํ๋ฉด
๋ถ๋ชจ class์ ์์ฑ์ ๋ถ๋ณ (immutable) ์ผ๋ก ๋ง๋๋ ๋ฐ ์ฌ์ฉ
ex)
์์ ๊ฐ์ฒด๋ฅผ ์์ฑํ๊ณ property์ ํ ๋นํ๋ ค๊ณ ํ๋ฉด error๊ฐ ๋ฐ์ํ๋ ๊ฒ ํ์ธ ๊ฐ๋ฅ
4. Better way to use @property
@property
@property method๋ก getter, setter๋ฅผ ๊ตฌํํ ๋ ์์๊ณผ ๋ค๋ฅด๊ฒ ๋์ํ์ง ์๋๋ก ์ฃผ์ํด์ผ ํจ
getter @property method์์ ๋ค๋ฅธ attribute๋ฅผ ์ค์ ํ์ง ๋ง์์ผ ํจ
@property.setter method ์์๋ง ๊ด๋ จ ๊ฐ์ฒด์ ์ํ๋ฅผ ์์ ํ๊ธฐ!!
์ฌ์ฌ์ฉ์ฑ ์ ํ์ด์ฌ์ ๋ด์ฅ๋ @property ์ ๊ฐ์ฅ ํฐ ๋ฌธ์ ์
@property๋ก decorate ํ๋ method๋ฅผ ๊ฐ์ class์ ์ํ ์ฌ๋ฌ ์์ฑ์์ ์ฌ์ฉ ํ ์ ์๋ค
+
๊ด๋ จ ์๋ class์์๋ ์ฌ์ฌ์ฉ ํ ์ ์๋ค๊ทธ๋์ ์ฌ์ฌ์ฉ ๊ฐ๋ฅํ @property method์์๋ descriptor protocol ์ ์ฌ์ฉํ๋ ๊ฒ์ด ์ข๋ค
+
Descriptor Protocol
Descriptor class๋ ๋ฐ๋ณต ์ฝ๋ ์์ด๋ method๋ฅผ ์ฌ์ฌ์ฉ ํ ์ ์๊ฒ ํด์ฃผ๋
__get__
๊ณผ__set__
method ๋ฅผ ์ ๊ณต ํ ์ ์๋คํ๋์ class์ ์๋ก ๋ค๋ฅธ ๋ง์ ์์ฑ์ ๊ฐ์ logic์ ์ฌ์ฌ์ฉ ํ ์ ์๋ค
Last updated
Was this helpful?