首 页IT知识库收藏内容
当前位置:翔宇亭IT乐园IT知识库Python

Python delattr()方法

减小字体 增大字体 作者:本站  来源:本站整理  发布时间:2021-10-09 18:10:04

微信搜索本站订阅号:优雅的代码。欢迎关注。
优雅的代码

Python delattr()是Python的内置函数,其作用是删除一个对象的指定属性。

语法格式

delattr(object, name)

参数

object:某类的对象;

name:字符串类型,代表对象的一个属性名称。

返回值

该函数没有返回值

 

使用举例

下面使用若干例子来说明delattr()函数的具体使用方法。

class Student:
    id = '001'
    name = '丁涛'
    def __init__(self, id,name,age):
        self.id = id
        self.name = name
        self.age = age

stu = Student('002', '丁当', 23)
print(stu.name)
print(Student.name)
delattr(Student, 'name')
print(stu.name)
print(Student.name)

输出内容如下:

丁当
丁涛
丁当
Traceback (most recent call last):
  File "D:/PY/delattr.py", line 14, in <module>
    print(Student.name)
AttributeError: type object 'Student' has no attribute 'name'
从上面的输出来看:

删除类的属性name后,再次使用时会引发AttributeError错误。但未影响使用类定义的对象。

class Student:
    id = '001'
    name = '丁涛'
    def __init__(self, id,name,age):
        self.id = id
        self.name = name
        self.age = age

stu = Student('002', '丁当', 23)
print(Student.name)
print
(stu.name)
delattr(stu, 'name')
print(Student.name)
print(stu.name)

输出内容如下:

丁涛
丁当
-------
丁涛
丁涛

从上面输出来看:

当删除了类对象的属性后,如果类中有同名的属性时,则使用类的属性值。

如果类中未定义对应的属性,则会引发下面的错误:

Traceback (most recent call last):
  File "D:/PY/delattr.py", line 16, in <module>
    print(stu.name)
AttributeError: 'Student' object has no attribute 'name'

如果一个类或类的对象没有对应的属性,将引发下面的错误:

Traceback (most recent call last):
  File "D:/PY/delattr.py", line 12, in <module>
    delattr(Student, 'name')
AttributeError: name

使用del操作符删除对象的属性

使用python的 del 操作符也可以删除类的一个属性,其语法格式如下:

del className.attributeName

看下面的例子:

class Student:
    id = '001'
    name = '丁涛'
    def __init__(self, id,name,age):
        self.id = id
        self.name = name
        self.age = age

stu = Student('002', '丁当', 23)
print(Student.name)
print
(stu.name)
del Student.name
print(stu.name)
print(Student.name)

输出内容如下:

丁涛
丁当
丁当
Traceback (most recent call last):
  File "D:/01Lesson/PY/delattr.py", line 25, in <module>
    print(Student.name)
AttributeError: type object 'Student' has no attribute 'name'

 从输出来看,其与delattr()函数的功能相同。


以上讲述了Python内置函数delattr()的使用方法以及del操作符的使用。如有问题欢迎留言。

如需转载,请注明出处:翔宇亭IT乐园(http://www.biye5u.com),并给出本文链接地址:

http://www.biye5u.com/article/python/2021/6540.html

微信搜索“优雅的代码”关注本站的公众号,或直接使用微信扫描下面二维码关注本站公众号,以获取最新内容。

个人成长离不开各位的关注,你的关注就是我继续前行的动力。

知识评论评论内容只代表网友观点,与本站立场无关!

   评论摘要(共 0 条,得分 0 分,平均 0 分) 查看完整评论
愿您的精彩评论引起共鸣,带来思考和价值。
用户名: 查看更多评论
分 值:100分 90分 80分 70分 60分 40分 20分
内 容:
验证码:
关于本站 | 网站帮助 | 广告合作 | 网站声明 | 友情连接 | 网站地图
本站部分内容来自互联网,如有侵权,请来信告之,谢谢!
Copyright © 2007-2024 biye5u.com. All Rights Reserved.