Today I Learned
Python에서 setattr() 함수를 활용하여 객체 속성 업데이트하기
- Python에서는 setattr() 함수를 사용하여 객체의 속성 값을 동적으로 설정할 수 있다. 약간 데이터의 일괄적 업데이트나 동적인 속성 할당 시에 주로 사용됨
for attr, value in validated_data.items():
setattr(instance, attr, value)
위의 예시 코드는 for 루프를 통해 validated_data 딕셔너리의 각 항목을 반복하면서 instance 객체의 속성을 업데이트하는데,
각 항목의 키(attr)는 instance의 속성 이름이 되고, 값(value)은 해당 속성에 할당
예를 들어, validated_data가 {'address': 'New Address', 'zip_code': '12345'}와 같이 주어진다면, 아래와 같이 실행됨
setattr(instance, 'address', 'New Address')
setattr(instance, 'zip_code', '12345')
=> instance 객체의 address와 zip_code 속성이 각각 'New Address'와 '12345'로 업데이트됨
setattr() 함수는 속성 이름과 값을 동적으로 설정할 수 있기 때문에, 프로그램의 유연성과 확장성을 높여준다.
Python에서는 객체의 속성을 직접 업데이트하는 것 외에도, getattr() 함수를 사용하여 속성 값을 가져오거나 hasattr() 함수를 사용하여 속성의 존재 여부를 확인하는 등의 다양한 속성 관련 작업을 수행할 수 있습니다.
Python에서 getattr() 함수와 hasattr() 함수를 활용하여 객체 속성 다루기
두 함수들은 속성에 대한 접근이 필요한 경우 유용하게 사용할 수 있다!
1. getattr() 함수
- getattr() 함수는 객체의 속성 값을 가져오는 데 사용
- 세 가지 매개변수를 받음 (객체, 속성 이름, 기본값(선택))
=> 속성 이름에 해당하는 속성 값을 반환하고, 속성이 존재하지 않을 경우 기본값 반환
value = getattr(obj, 'attribute_name', default_value)
위의 코드에서 obj = 객체, attribute_name = 속성의 이름, default_value = 속성이 존재하지 않을 경우 반환될 기본값
2. hasattr() 함수
- hasattr() 함수는 객체가 특정 속성을 가지고 있는지 여부를 확인하는 데 사용
- 이 함수는 두 가지 매개변수를 받음 (객체, 속성 이름)
=> 해당 속성이 존재하면 True를 반환, 그렇지 않으면 False를 반환.
has_attribute = hasattr(obj, 'attribute_name')
위의 코드에서 obj = 객체, attribute_name = 확인하고자 하는 속성의 이름
has_attribute 변수에는 해당 속성이 존재하는지 여부에 따라 True 또는 False 저장
'내일배움캠프 > 내일배움캠프 TIL' 카테고리의 다른 글
내일배움 캠프 TIL 79일차 (0) | 2023.07.03 |
---|---|
내일배움 캠프 TIL 78일차 - 젠킨스로 CI/CD 배포 환경 구축하기 02 (0) | 2023.07.03 |
내일배움 캠프 TIL 77일차 - 젠킨스로 CI/CD 배포 환경 구축하기 01 (0) | 2023.07.03 |
내일배움캠프 TIL 76일차 - KPT 중간 발표 회고록 (0) | 2023.06.26 |
내일배움캠프 TIL 75일차 (0) | 2023.06.25 |