Python delattr()
delattr() จะลบแอตทริบิวต์ออกจากวัตถุหากวัตถุอนุญาต
ไวยากรณ์
ไวยากรณ์ของ delattr() คือ −
delattr(object, name)
วิธี delattr() ใช้พารามิเตอร์สองตัว -
delattr() ไม่คืนค่าใด ๆ (คืนค่า None) โดยจะลบแอตทริบิวต์เท่านั้น (หากวัตถุอนุญาต)
ตัวอย่าง
class Coordinate:
x = 12
y = -7
z = 0
point1 = Coordinate()
print('x = ',point1.x)
print('y = ',point1.y)
print('z = ',point1.z)
delattr(Coordinate, 'z')
print('--After deleting z attribute--')
print('x = ',point1.x)
print('y = ',point1.y)
# Raises Error
print('z = ',point1.z) ผลลัพธ์
สิ่งนี้ให้ผลลัพธ์
Traceback (most recent call last):
('x = ', 12)
('y = ', -7)
File "C:/Users/~.py", line 28, in <module>
('z = ', 0)
print('z = ',point1.z)
--After deleting z attribute--
('x = ', 12)
AttributeError: Coordinate instance has no attribute 'z'
('y = ', -7)