在 Python 中使用 del 关键字 您所在的位置:网站首页 del语句python 在 Python 中使用 del 关键字

在 Python 中使用 del 关键字

2023-07-14 19:25| 来源: 网络整理| 查看: 265

在 Python 中使用 del 语句删除变量 在 Python 中使用 del 语句删除列表 在 Python 中使用 del 语句删除字典元素 用 Python 中的 del 语句删除用户定义的类对象

在本教程中,我们将讨论 Python 中 del 语句的用法。

del 语句是用来删除对象的。由于 Python 面向对象的特性,所有能容纳数据的东西都是一个对象。所以,del 语句可以用来删除变量、类对象、列表等。

del 语句的语法为:

del object_name

它通过从本地和全局命名空间中删除 object_name 来工作。

在 Python 中使用 del 语句删除变量 variable = "This is a variable" print(variable) del variable print(variable)

输出:

This is a variable --------------------------------------------------------------------------- NameError Traceback (most recent call last) in () 2 print(variable) 3 del variable ----> 4 print(variable) NameError: name 'variable' is not defined

上述程序显示了 variable 的值,然后给出了 NameError。这是因为在使用 del 语句后,variable 已经从命名空间中删除了。

在 Python 中使用 del 语句删除列表 List = ["One", "Two", "Three"] print(List) del List print(List)

输出:

['One', 'Two', 'Three'] --------------------------------------------------------------------------- NameError Traceback (most recent call last) in () 2 print(List) 3 del List ----> 4 print(List) NameError: name 'List' is not defined

与前面的例子类似,List 这个名字已经从命名空间中删除。

我们也可以使用 del 语句对一个列表进行切片。

List = ["One", "Two", "Three"] print(List) del List[1] print(List)

输出:

['One', 'Two', 'Three'] ['One', 'Three']

它删除了索引为 1 的列表元素。

在 Python 中使用 del 语句删除字典元素 dictionary = {"key1" : "value1", "key2" : "value2", "key3" : "value3"} print(dictionary) del dictionary["key2"] print(dictionary)

输出:

{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'} {'key1': 'value1', 'key3': 'value3'} 用 Python 中的 del 语句删除用户定义的类对象 class MyClass: def myFunction(self): print('Hello') class1 = MyClass() class1.myFunction() del class1 class1.myFunction()

输出:

Hello --------------------------------------------------------------------------- NameError Traceback (most recent call last) in () 6 class1.myFunction() 7 del class1 ----> 8 class1.myFunction() NameError: name 'class1' is not defined


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有