Python del statement and delattr() function is used to delete the attribute of an object. Both of them does the exact same thing. However, delattr() function is useful when we want to delete an attribute dynamically, for example deleting attribute of an object based on user input.
Python del语句和delattr()函数用于删除对象的属性。 他们两个都做完全相同的事情。 但是,当我们要动态删除属性(例如,根据用户输入删除对象的属性)时,delattr()函数很有用。
Python del语句 (Python del statement)
Let’s say we have Employee class defined as:
假设我们将Employee类定义为:
class Employee:
id = -1
name = ''
def __init__(self, i, n, r):
self.id = i
self.name = n
self.role = r
def __str__(self):
return "Employee[id={}, name={}, role={}]".format(self.id, self.name, self.role)
Notice that id and name are class variables whereas the role is instance variable.
注意, id和name是类变量,而role是实例变量。
Let’s see some example of using del statement to delete class attributes.
让我们看一些使用del 语句删除类属性的示例。
e = Employee(10, 'Pankaj', 'CEO')
print(e)
print(e.id)
print(e.name)
print(e.role)
# del with class attribute
del e.id
print(e)
print(e.id)
del e.name
print(e.name)
Output:
输出:
Employee[id=10, name=Pankaj, role=CEO]
10
Pankaj
CEO
Employee[id=-1, name=Pankaj, role=CEO]
-1
So when we deleted class variable using del statement, in further access default value is returned.
因此,当我们使用del语句删除类变量时,在进一步访问中将返回默认值。
Now let’s see what happens when we try to delete the instance variable and then access it.
现在,让我们看看尝试删除实例变量然后访问它时会发生什么。
del e.role
print(e.role)
Output:
输出:
AttributeError: 'Employee' object has no attribute 'role'
So when instance attribute is deleted, future access to them is causing AttributeError.
因此,当实例属性被删除时,将来对它们的访问将导致AttributeError。
Python delattr() (Python delattr())
Python delattr() syntax is:
Python delattr()语法为:
delattr(object, name)
The first argument is the object whose attribute we want to delete. The second argument is the name of the attribute we want to delete from the object.
第一个参数是我们要删除其属性的对象。 第二个参数是我们要从对象中删除的属性的名称。
Let’s look at some delattr() function examples.
让我们看一些delattr()函数示例。
e = Employee(10, 'Pankaj', 'CEO')
print(e)
print(e.id)
print(e.name)
print(e.role)
delattr(e, 'id')
print(e)
print(e.id)
delattr(e, 'name')
print(e.name)
Output:
输出:
Employee[id=10, name=Pankaj, role=CEO]
10
Pankaj
CEO
Employee[id=-1, name=Pankaj, role=CEO]
-1
Let’s see what happens when we try to delete the instance variable ‘role’.
让我们看看尝试删除实例变量“角色”时会发生什么。
delattr(e, 'role')
print(e.role)
Output:
输出:
AttributeError: 'Employee' object has no attribute 'role'
Python del vs delattr() (Python del vs delattr())
It’s clear from the above examples that del statement and delattr() function does the same thing. So when to use del statement and when to go for delattr() function?
从上面的示例可以明显看出,del语句和delattr()函数具有相同的作用。 那么什么时候使用del语句,什么时候使用delattr()函数呢?
If you are deleting an object attribute statically in the program, it makes sense to use del statement. However, delattr() function is the only way when you want to dynamically assign the attribute to delete. For example, taking user input to delete an object attribute. Let’s see this with a simple example.
如果要在程序中静态删除对象属性,则可以使用del语句。 但是,当您要动态分配要删除的属性时,delattr()函数是唯一的方法。 例如,接受用户输入以删除对象属性。 让我们用一个简单的例子来看一下。
# delattr() benefit with dynamic attribute deletion
e = Employee(20, 'Lisa', 'Editor')
print(e)
attr = input('Please enter attribute to delete, valid values are id, name and role\n')
delattr(e, attr)
print(e)
Output:
输出:
Employee[id=20, name=Lisa, role=Editor]
Please enter attribute to delete, valid values are id, name and role
id
Employee[id=-1, name=Lisa, role=Editor]
Note that I am deleting the class variable. Below image shows the output when we are trying to delete instance variable and later our program is trying to access it.
请注意,我要删除类变量。 下图显示了当我们尝试删除实例变量并且稍后我们的程序尝试访问它时的输出。
Employee[id=20, name=Lisa, role=Editor]
Please enter attribute to delete, valid values are id, name and role
role
Traceback (most recent call last):
File "/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/python_del_delattr_examples.py", line 47, in
print(e)
File "/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/python_del_delattr_examples.py", line 11, in __str__
return "Employee[id={}, name={}, role={}]".format(self.id, self.name, self.role)
AttributeError: 'Employee' object has no attribute 'role'
Python Delete属性vs设置为None (Python delete attribute vs setting to None)
If you want to reuse the attribute, you can set it to None. However, if you delete the instance attribute then you will get an error in accessing it unless you set it again.
如果要重用该属性,可以将其设置为None。 但是,如果删除实例属性,那么除非再次设置它,否则在访问它时会遇到错误。
# set to None vs del/delattr
e.role = None
print('Role =', e.role)
del e.role
e.role = 'CEO'
print('Role =', e.role)
Output:
输出:
Role = None
Role = CEO
删除已删除的属性 (Deleting already deleted attribute)
If we try to delete an already deleted attribute, we will get AttributeError.
如果我们尝试删除一个已经删除的属性,我们将得到AttributeError 。
e = Employee(20, 'Lisa', 'Editor')
del e.id
# del e.id # AttributeError: id
delattr(e, 'name')
# delattr(e, 'name')  # AttributeError: name
删除不存在的属性 (Deleting Non Existing Attribute)
If we try to delete an object attribute that doesn’t exist, we will get AttributeError.
如果我们尝试删除不存在的对象属性,则会得到AttributeError 。
# del e.x  # AttributeError: x
# delattr(e, 'x')  # AttributeError: x
That’s all for python del statement and delattr() function.
这就是python del语句和delattr()函数的全部。
GitHub Repository.
GitHub存储库中检出完整的python脚本和更多Python示例。
Reference: Official Documentation


翻译自: https://www.journaldev.com/22803/python-del-statement-delattr-function