Python delattr()是Python的內(nèi)置函數(shù),其作用是刪除一個(gè)對(duì)象的指定屬性。
delattr(object, name)
object:某類的對(duì)象;
name:字符串類型,代表對(duì)象的一個(gè)屬性名稱。
該函數(shù)沒(méi)有返回值
下面使用若干例子來(lái)說(shuō)明delattr()函數(shù)的具體使用方法。
class Student:
id = '001'
name = '丁濤'
def __init__(self, id,name,age):
self.id = id
self.name = name
self.age = age
stu = Student('002', '丁當(dāng)', 23)
print(stu.name)
print(Student.name)
delattr(Student, 'name')
print(stu.name)
print(Student.name)
輸出內(nèi)容如下:
丁當(dāng)
從上面的輸出來(lái)看:
丁濤
丁當(dāng)
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后,再次使用時(shí)會(huì)引發(fā)AttributeError錯(cuò)誤。但未影響使用類定義的對(duì)象。
class Student:
id = '001'
name = '丁濤'
def __init__(self, id,name,age):
self.id = id
self.name = name
self.age = age
stu = Student('002', '丁當(dāng)', 23)
print(Student.name)
print(stu.name)
delattr(stu, 'name')
print(Student.name)
print(stu.name)
輸出內(nèi)容如下:
丁濤
丁當(dāng)
-------
丁濤
丁濤
從上面輸出來(lái)看:
當(dāng)刪除了類對(duì)象的屬性后,如果類中有同名的屬性時(shí),則使用類的屬性值。
如果類中未定義對(duì)應(yīng)的屬性,則會(huì)引發(fā)下面的錯(cuò)誤:
Traceback (most recent call last):
File "D:/PY/delattr.py", line 16, in <module>
print(stu.name)
AttributeError: 'Student' object has no attribute 'name'
如果一個(gè)類或類的對(duì)象沒(méi)有對(duì)應(yīng)的屬性,將引發(fā)下面的錯(cuò)誤:
Traceback (most recent call last):
File "D:/PY/delattr.py", line 12, in <module>
delattr(Student, 'name')
AttributeError: name
使用python的 del 操作符也可以刪除類的一個(gè)屬性,其語(yǔ)法格式如下:
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', '丁當(dāng)', 23)
print(Student.name)
print(stu.name)
del Student.name
print(stu.name)
print(Student.name)
輸出內(nèi)容如下:
丁濤
丁當(dāng)
丁當(dāng)
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'
從輸出來(lái)看,其與delattr()函數(shù)的功能相同。
新聞熱點(diǎn)
疑難解答
圖片精選