일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- Database
- KAKAO
- Python
- Mac
- DB
- format
- PostgreSQL
- file
- Windows
- judge
- Linux
- Converting
- Flask
- enV
- git
- LLM
- Package
- GitLab
- CUDA
- Laravel
- pandas
- pytorch
- Container
- AI
- Paper
- numpy
- TORCH
- evaluation
- list
- docker
Archives
- Today
- Total
Daily Develope
[Python] 클래스 속성의 getter & setter 정의 본문
방법 1. 내장 property method
클래스의 속성값에 대한 getter, setter, destructor 동작을 method로 정의하고,
내장함수인 property를 사용해 해당하는 속성과 연결시켜 사용.
샘플코드
# Python program showing a use of property() function
class Geeks:
def __init__(self):
self._age = 0
# function to get value of _age
def get_age(self):
print("getter method called")
return self._age
# function to set value of _age
def set_age(self, a):
print("setter method called")
self._age = a
# function to delete _age attribute
def del_age(self):
del self._age
age = property(get_age, set_age, del_age)
mark = Geeks()
mark.age = 10
print(mark.age)
샘플코드의 출력
setter method called
getter method called
10
방법 2. 내장 decorator
속성의 getter, setter method 정의 시 내장 decorator인 @property를 사용
(*decorator는 보편적으로 사용되는 동작을 정의하고, 특정 function 호출시 해당 동작이 함께 수행될 수 있도록 정의하고 있는 function 동작에 대한 function 정의라고 볼 수 있다. (상세한 설명은 참조의 링크 확인))
샘플코드
# Python program showing the use of @property
class Geeks:
def __init__(self):
self._age = 0
# using property decorator
# a getter function
@property
def age(self):
print("getter method called")
return self._age
# a setter function
@age.setter
def age(self, a):
if(a < 18):
raise ValueError("Sorry you age is below eligibility criteria")
print("setter method called")
self._age = a
mark = Geeks()
mark.age = 19
print(mark.age)
샘플코드의 출력
setter method called
getter method called
19
참조
'Develope > Python' 카테고리의 다른 글
[Python] Pickle library (object serialization) (1) | 2023.10.17 |
---|---|
[Python] Postgresql 연동 / 연결 코드 샘플 (0) | 2023.10.03 |
[Python] 알면 도움되는 자주쓰는 문법 (tips) (0) | 2023.04.10 |
[Python] 문법 (grammer) 예제로 간단 정리 (0) | 2023.04.10 |
[Python] Multi processing 멀티 프로세싱 (0) | 2023.02.15 |