파이썬에서는 delattr() 함수와 del 키워드를 사용해 클래스의 속성(attribute)을 삭제할 수 있습니다. 두 방법 모두 동일한 결과를 내지만, delattr()는 문자열 형태로 속성 이름을 전달하기 때문에 실행 중에 동적으로 속성을 삭제하는 데 유리하고, del은 문법이 더 간결하고 명시적이라는 차이가 있습니다.
delattr() 함수 사용법
delattr()는 객체와 삭제하려는 속성 이름을 인자로 받아 해당 속성을 제거합니다.
구문: delattr(객체_이름, 속성_이름) - 객체_이름: 클래스로부터 생성된 객체의 이름 - 속성_이름: 삭제할 속성의 이름 (문자열로 전달)
예제 1: 기본 클래스 출력
먼저 고객 ID를 속성으로 가지는 custclass라는 클래스를 정의하고, 이를 객체로 만들어 각 속성 값을 출력해 보겠습니다.
class custclass:
custid1 = 0
custid2 = 1
custid3 = 2
customer = custclass()
print(customer.custid1)
print(customer.custid2)
print(customer.custid3)출력 결과
0 1 2
예제 2: delattr()로 속성 삭제
이번에는 delattr() 함수를 적용해 custid3 속성을 삭제한 뒤 다시 출력해 보겠습니다. 속성이 이미 제거되었기 때문에 접근 시 오류가 발생합니다.
class custclass:
custid1 = 0
custid2 = 1
custid3 = 2
customer = custclass()
print(customer.custid1)
print(customer.custid2)
delattr(custclass, 'custid3')
print(customer.custid3)출력 결과
0 1 Traceback (most recent call last): File "xxx.py", line 13, in print(customer.custid3) AttributeError: 'custclass' object has no attribute 'custid3'
앞의 두 속성은 정상적으로 출력되지만, 삭제된 custid3에 접근하면 AttributeError가 발생하는 것을 확인할 수 있습니다.
del 키워드 사용법
del 키워드는 점(.) 표기법으로 객체의 속성에 직접 접근하여 삭제합니다. delattr()와 달리 속성 이름을 문자열로 감싸지 않는다는 점이 문법상의 주요 차이입니다.
구문: del(객체_이름.속성_이름) - 객체_이름: 클래스로부터 생성된 객체의 이름 - 속성_이름: 삭제할 속성의 이름
예제 3: del로 속성 삭제
같은 예제를 이번에는 del 키워드로 실행해 보겠습니다.
class custclass:
custid1 = 0
custid2 = 1
custid3 = 2
customer = custclass()
print(customer.custid1)
print(customer.custid2)
del(custclass.custid3)
print(customer.custid3)출력 결과
0 1 Traceback (most recent call last): File "xxx.py", line 13, in print(customer.custid3) AttributeError: 'custclass' object has no attribute 'custid3'
정리
delattr()와 del 모두 클래스나 객체의 속성을 삭제하는 데 사용됩니다. 속성 이름을 변수나 문자열로 다뤄야 하는 동적인 상황에서는 delattr()가 적합하고, 코드 가독성과 명시성이 중요한 일반적인 경우에는 del 키워드를 사용하는 것이 좋습니다. 단, 삭제된 속성에 다시 접근하면 AttributeError가 발생하므로 주의해야 합니다.