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>
原創文章,作者:簡單一點,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/127722.html