英文文檔:
-
delattr(object, name) -
This is a relative of
setattr(). The arguments are an object and a string. The string must be the name of one of the object’s attributes. The function deletes the named attribute, provided the object allows it. For example,delattr(x, 'foobar')is equivalent todel x.foobar. - 說明:
- 1. 函數作用用來刪除指定對象的指定名稱的屬性,和setattr函數作用相反。
#定義類A >>> class A: def __init__(self,name): self.name = name def sayHello(self): print('hello',self.name) #測試屬性和方法 >>> a.name '小麥' >>> a.sayHello() hello 小麥 #刪除屬性 >>> delattr(a,'name') >>> a.name Traceback (most recent call last): File "<pyshell#47>", line 1, in <module> a.name AttributeError: 'A' object has no attribute 'name'
2. 當屬性不存在的時候,會報錯。
>>> a.name #屬性name已經刪掉,不存在 Traceback (most recent call last): File "<pyshell#47>", line 1, in <module> a.name AttributeError: 'A' object has no attribute 'name' >>> delattr(a,'name') #再刪除會報錯 Traceback (most recent call last): File "<pyshell#48>", line 1, in <module> delattr(a,'name') AttributeError: name
3. 不能刪除對象的方法。
>>> a.sayHello <bound method A.sayHello of <__main__.A object at 0x03F014B0>> >>> delattr(a,'sayHello') #不能用於刪除方法 Traceback (most recent call last): File "<pyshell#50>", line 1, in <module> delattr(a,'sayHello') AttributeError: sayHello >>>
