Hai hàm này dùng để xóa thuộc tính (attribute) khỏi lớp (class). delattr() cho phép xóa động (tại runtime) bằng cách truyền tên thuộc tính dưới dạng chuỗi, trong khi del là từ khóa dùng để xóa tường minh.
Sử dụng delattr()
Cú pháp: delattr(đối_tượng, tên_thuộc_tính) # đối_tượng: instance của lớp # tên_thuộc_tính: chuỗi tên thuộc tính cần xóa
Ví dụ 1 - Tạo lớp và in thuộc tính
class CustClass:
custid1 = 0
custid2 = 1
custid3 = 2
customer = CustClass()
print(customer.custid1) # 0
print(customer.custid2) # 1
print(customer.custid3) # 2
Kết quả
0 1 2
Ví dụ 2 - Xóa thuộc tính bằng delattr()
class CustClass:
custid1 = 0
custid2 = 1
custid3 = 2
customer = CustClass()
print(customer.custid1)
print(customer.custid2)
delattr(CustClass, 'custid3')
print(customer.custid3) # Gây lỗi AttributeError
Kết quả
0 1 Traceback (most recent call last): File "xxx.py", line 13, inprint(customer.custid3) AttributeError: 'CustClass' object has no attribute 'custid3'
Sử dụng del
Cú pháp: del(đối_tượng.tên_thuộc_tính)
Ví dụ - Xóa bằng del
class CustClass:
custid1 = 0
custid2 = 1
custid3 = 2
customer = CustClass()
print(customer.custid1)
print(customer.custid2)
del(CustClass.custid3)
print(customer.custid3) # Gây lỗi AttributeError
Kết quả
0 1 Traceback (most recent call last): File "xxx.py", line 13, inprint(customer.custid3) AttributeError: 'CustClass' object has no attribute 'custid3'
Lưu ý quan trọng
delattr()nhận tên thuộc tính là chuỗi, hữu ích khi tên thuộc tính chỉ biết tại runtime.dellà từ khóa, dùng trực tiếp tên thuộc tính.- Cả hai đều xóa thuộc tính ở cấp độ lớp (class), ảnh hưởng đến tất cả instance.