delattr() 函数将一个对象作为参数,并从该对象中删除一个属性。
delattr(object, name) #where name is the name of attribute
该函数接受一个对象作为参数,要删除的属性可以作为可选参数传递。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| 一个对象 | 要从中删除属性的对象。 | 必需 |
| 属性 | 要删除的属性名称。 | 可选 |
delattr() 函数不返回任何内容。它只从对象中删除属性。
class Student:
name = "Ram" age = 22
course = "Bachelors"
Student1 = Student()
delattr(Student, 'age') #Removing age attribute
print("Student's name is ",Student 1.name)
print("Student's country is ",Student 1.country)
print("Student's age is ",Student 1.age) # Raises error since age is not found
输出
Student's name is John Student's country is Norway AttributeError: 'Student' object has no attribute 'age'
class Coordinate:
x = 20
y = -15
z = 0
value1 = Coordinate()
print('x = ',value1.x)
print('y = ',value1.y)
print('z = ',value1.z)
delattr(Coordinate, 'z')
print('--After deleting z attribute--')
print('x = ',value1.x)
print('y = ',value1.y)
# Raises Error
print('z = ',value1.z)
输出
x = 20 y = -15 z = 0 --After deleting z attribute-- x = 20 y = -15 Traceback (most recent call last): File "python", line 19, inAttributeError: 'Coordinate' object has no attribute 'z'