delattr() xóa attribute từ object nếu object cho phép.
Syntax: delattr(object, name)
- 2 tham số: object và tên attribute (string)
- Trả về
None - Chỉ xóa attribute (nếu object cho phép)
Ví dụ
class Coordinate:
x = 12
y = -7
z = 0
point1 = Coordinate()
print('x =', point1.x) # 12
print('y =', point1.y) # -7
print('z =', point1.z) # 0
delattr(Coordinate, 'z')
print('--After deleting z attribute--')
print('x =', point1.x) # 12
print('y =', point1.y) # -7
print('z =', point1.z) # AttributeError
Kết quả
x = 12 y = -7 z = 0 --After deleting z attribute-- x = 12 y = -7 AttributeError: 'Coordinate' object has no attribute 'z'
Lưu ý: Xóa class attribute ảnh hưởng đến tất cả instance. Không thể xóa attribute read-only (như built-in type attribute).