Python built-in functions (14) -- delattr, pythondelattr
English document:
-
delattr(
Object,
Name)
-
This is a relative
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
del x.foobar.
-
Note:
-
-
1. The function is used to delete the attribute of the specified name of the specified object, which is opposite to the setattr function.
# Define class A >>> class A: def _ init _ (self, name): self. name = name def sayHello (self): print ('hello', self. name) # test attributes and Methods>. name 'wheat '>. sayHello () hello wheat # Delete attribute >>> delattr (a, 'name') >>>. nameTraceback (most recent call last): File "<pyshell #47>", line 1, in <module>. nameAttributeError: 'A 'object has no attribute 'name'
2. If the property does not exist, an error is returned.
>>>. Name # The property name has been deleted. Traceback (most recent call last): File "<pyshell #47>", line 1, in <module>. nameAttributeError: 'A' object has no attribute 'name' >>> delattr (A, 'name') # The error Traceback (most recent call last) is returned when you delete the file ): file "<pyshell #48>", line 1, in <module> delattr (a, 'name') AttributeError: name
3. Methods of objects cannot be deleted.
>>>. SayHello <bound method. sayHello of <__ main __. A object at 0x03F014B0 >>>> delattr (a, 'sayhel') # The method Traceback (most recent call last) cannot be deleted: File "<pyshell #50> ", line 1, in <module> delattr (a, 'sayhel') AttributeError: sayHello >>>