- ·上一篇内容:Python complex()方法
- ·下一篇内容:python中的main()函数
Python delattr()方法
微信搜索本站订阅号:优雅的代码。欢迎关注。
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
微信搜索“优雅的代码”关注本站的公众号,或直接使用微信扫描下面二维码关注本站公众号,以获取最新内容。
个人成长离不开各位的关注,你的关注就是我继续前行的动力。