delattr()
函数将一个对象作为参数,并从该对象中移除一个属性。
**delattr(object, name)** #where name is the name of attribute
delattr()
参数:
该函数将一个对象作为参数,要删除的属性可以作为可选参数传递。
参数 | 描述 | 必需/可选 |
---|---|---|
一个对象 | 要从中删除属性的对象 | 需要 |
属性 | 要移除的属性的名称 | 可选择的 |
延迟()返回值
delattr()
函数不返回任何内容。它只从对象中移除属性
Python 中delattr()
方法的示例
示例 1:从对象中移除属性
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'
示例delattr()
是如何工作的?
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, in <module>AttributeError: 'Coordinate' object has no attribute 'z'</module>
文章评论