Python范例中的del关键字

Python del关键字

del是python中的关键字(区分大小写),用于删除对象(如类的对象,变量,列表,列表的一部分等)。

注意:删除对象后–如果尝试使用它,则会发生“ NameError”

del关键字的语法

    del object_name

示例

    Input:
    num = -21

    # 删除
    del a

    # 尝试打印-将会发生错误    print(num)

    Output:
    NameError: name 'num' is not defined

关键字del的Python示例

示例1:删除变量。

# python代码演示示例 
# del关键字 

# 删除变量 

# declare a variable & assign a value

a = 100

# 打印值 
print("a = ", a)

# 删除变量
del a 

# 打印值 - NameError will be generated
print("a = ", a)

输出结果

a =  100
Traceback (most recent call last):
  File "/home/main.py", line 17, in <module>
    print("a = ", a)
NameError: name 'a' is not defined

示例2:删除类的对象。

# python代码演示示例 
# del关键字 

# 删除类的对象

# 定义一个类
class student:
    name = "Aman"
    age = 21

# 主要代码
# 向student类声明对象
std = student()# 打印值
print("Name: ", std.name)
print("Age: ", std.age)

# 删除对象 
del std

# 打印值将生成NameError
print("Name: ", std.name)
print("Age: ", std.age)

输出结果

Name:  Aman
Age:  21
Traceback (most recent call last):
  File "/home/main.py", line 23, in <module>
    print("Name: ", std.name)
NameError: name 'std' is not defined