이번 편은 변수가 있는지 확인하기 (hasattr / getattr / setattr) 이다.
1. hasattr
클래스로 만든 객체에 해당 변수가 있는지 확인한다. 있다면 True, 없다면 False
class check():
check1 = 10
check2 = 20
check3 = 30
test = check()
print(hasattr(test, "check1"))
print(hasattr(test, "check2"))
print(hasattr(test, "check3"))
print(hasattr(test, "check4"))
True
True
True
False
2. getattr
클래스로 만든 객체에 해당 변수가 있는지 확인하고 해당 값을 가져온다.
class check():
check1 = 10
check2 = 20
check3 = 30
test = check()
print(getattr(test, "check1"))
print(getattr(test, "check2"))
print(getattr(test, "check3"))
10
20
30
3. setattr
클래스로 만든 객체에 해당 변수가 있는지 확인하고 해당 변수의 값을 변경한다. 아래 setattr로 변경한 값이 출력되는 것을 알 수 있다.
class check():
check1 = 10
check2 = 20
check3 = 30
test = check()
setattr(test, "check1" ,100)
setattr(test, "check2" ,200)
setattr(test, "check3" ,300)
print(getattr(test, "check1"))
print(getattr(test, "check2"))
print(getattr(test, "check3"))
100
200
300
끝!
'Python > Study' 카테고리의 다른 글
python 기초 - queue (0) | 2023.01.16 |
---|---|
python 기초 - decorator (0) | 2023.01.15 |
python 기초 - 지역변수, 전역변수, 동적변수 (local, global, globals 등) (0) | 2023.01.15 |
python 기초 - 예외 처리 (try, except, finally, Error처리) (1) | 2023.01.15 |
python 기초 - 한줄 수식 정리 (for, if 등) + zip, *zip (0) | 2023.01.15 |