250x250
반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 유튜브 API
- top_k
- gather_nd
- Airflow
- grad-cam
- XAI
- 공분산
- login crawling
- 상관관계
- subdag
- API Gateway
- Retry
- session 유지
- requests
- GenericGBQException
- spark udf
- GCP
- TensorFlow
- integrated gradient
- tensorflow text
- airflow subdag
- UDF
- API
- chatGPT
- hadoop
- flask
- BigQuery
- correlation
- Counterfactual Explanations
- youtube data
Archives
- Today
- Total
데이터과학 삼학년
property (getter, setter) 본문
반응형
@property 라는 데커레이터를 쓰는 것에 대해 알아본다.
먼저 @property class 내에서 getter와 setter 를 좀 더 편하게 적용하기 위해 사용할 수 있다.
getter 와 setter 는 무엇인가?
class Person:
def __init__(self):
self.__age = 0
def get_age(self): # getter
return self.__age
def set_age(self, value): # setter
self.__age = value
james = Person()
james.set_age(20)
print(james.get_age())
위 Person class에서 매개변수의 값을 받아오는 메서드는 get_age, 매개변수에 값을 세팅하는 것이 set_age가 된다.
여기서 값을 읽는 행위를 getter 라고 하고, 값을 setting하는 것을 setter라고 한다.
위 class 처럼 getter와 setter를 따로 method로 만들어 구현할 수 도 있지만,
@property 를 사용하면 보다 이쁘게(?) 표현할 수 있다.
class Person:
def __init__(self):
self.__age = 0
@property
def age(self): # getter
return self.__age
@age.setter
def age(self, value): # setter
self.__age = value
james = Person()
james.age = 20 # 인스턴스.속성 형식으로 접근하여 값 저장
print(james.age) # 인스턴스.속성 형식으로 값을 가져옴
getter에 @property 데커레이터를 적용해주고, 적용한 메서드명.setter를 동일한 메서드명 위에 데커레이터로 쌓으면 바한가지 method 명으로 getter와 setter를 둘 다 쓸 수 있다.
출처 : https://dojang.io/mod/page/view.php?id=2476
728x90
반응형
LIST
'Python' 카테고리의 다른 글
Instance method, Class method, Static method (1) | 2020.04.04 |
---|---|
문자열 포맷팅 (% operator, str.format, f-string) (0) | 2020.04.02 |
모듈, 패키지 개념 정리 (if __name__=='__main__': 쓰는 이유) (4) | 2020.03.23 |
OS 모듈 정리 (0) | 2020.03.02 |
Decorator (데커레이터) (0) | 2020.01.26 |
Comments