Python delattr()是Python的內置函數,其作用是刪除一個對象的指定屬性。
delattr(object, name)
object:某類的對象;
name:字符串類型,代表對象的一個屬性名稱。
該函數沒有返回值
下面使用若干例子來說明delattr()函數的具體使用方法。
class Student:
id = '001'
name = '丁濤'
def __init__(self, id,name,age):
self.id = id
self.name = name
self.age = age
stu = Student('002', '丁當', 23)
print(stu.name)
print(Student.name)
delattr(Student, 'name')
print(stu.name)
print(Student.name)
輸出內容如下:
丁當
從上面的輸出來看:
丁濤
丁當
Traceback (most recent call last):
File "D:/PY/delattr.py", line 14, in <module>
print(Student.name)
AttributeError: type object 'Student' has no attribute 'name'
刪除類的屬性name后,再次使用時會引發AttributeError錯誤。但未影響使用類定義的對象。
class Student:
id = '001'
name = '丁濤'
def __init__(self, id,name,age):
self.id = id
self.name = name
self.age = age
stu = Student('002', '丁當', 23)
print(Student.name)
print(stu.name)
delattr(stu, 'name')
print(Student.name)
print(stu.name)
輸出內容如下:
丁濤
丁當
-------
丁濤
丁濤
從上面輸出來看:
當刪除了類對象的屬性后,如果類中有同名的屬性時,則使用類的屬性值。
如果類中未定義對應的屬性,則會引發下面的錯誤:
Traceback (most recent call last):
File "D:/PY/delattr.py", line 16, in <module>
print(stu.name)
AttributeError: 'Student' object has no attribute 'name'
如果一個類或類的對象沒有對應的屬性,將引發下面的錯誤:
Traceback (most recent call last):
File "D:/PY/delattr.py", line 12, in <module>
delattr(Student, 'name')
AttributeError: name
使用python的 del 操作符也可以刪除類的一個屬性,其語法格式如下:
del className.attributeName
看下面的例子:
class Student:
id = '001'
name = '丁濤'
def __init__(self, id,name,age):
self.id = id
self.name = name
self.age = age
stu = Student('002', '丁當', 23)
print(Student.name)
print(stu.name)
del Student.name
print(stu.name)
print(Student.name)
輸出內容如下:
丁濤
丁當
丁當
Traceback (most recent call last):
File "D:/01Lesson/PY/delattr.py", line 25, in <module>
print(Student.name)
AttributeError: type object 'Student' has no attribute 'name'
從輸出來看,其與delattr()函數的功能相同。
新聞熱點
疑難解答